[英]Laravel 5.2 - Share data with all views
我记录了一个标题用户菜单,每个注册的用户都有一个余额导入,我想在我记录的标题部分用户中显示此余额,我试图使用VIEW SHARE,但是这样无法正常工作:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
//its just a dummy data object.
$balance = UserBalance::where('user_id', Auth::id())->first();
// Sharing - the error interested this section:
view()->share('balance', $balance->balance);
}
}
我的错误
AppServiceProvider.php第23行中的ErrorException:尝试获取非对象的属性
line 23 : view()->share('balance', $balance->balance);
菜单用户部分(在我所有视图的布局内):
@if (Auth::guest())
<li><a href="{{ url('login')}}">Accedi</a></li>
<li class="item-custom"><a href="{{url('register')}}">Registrati</a></li>
@else
<li class="hello-user">
Ciao {{Auth::user()->name}}
</li>
<li> Your Balance: {{$balance}}</li>
@endif
谢谢您的帮助!
这可能不是最佳答案,但是您是否考虑过将结果存储在Session中?
可以通过任何视图检查和读取会话。
if ($request->session()->has('balance')) {
$request->session()->get('balance', 0);
}
检查用户是否登录。 如果用户未通过身份验证,则Auth::user()->id
将不存在,您还需要检查$balance
。 如果查询返回null,则将显示错误。
AppServiceProvider.php第23行中的ErrorException:尝试获取非对象的属性
尝试这个:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
if(Auth::check()){
//its just a dummy data object.
$balance = UserBalance::where('user_id', Auth::user()->id)->first();
// Sharing - the error interested this section:
view()->share('balance', (count($balance) > 0) ? $balance->balance : 0);
}
}
}
您的Auth :: id()返回null或不检索会话ID。 因为Laravel会话是使用会话中间件处理的,并且所有中间件都在AppserviceProvider之前执行。 因此,它不会检索会话标识。您可以使用此代码。 因为view()-> composer clouser将在组成视图时执行。 然后您可以使用会话ID
public function boot()
{
$this->getBalance();
}
public function getBalance()
{
view()->composer('*', function ($view) {
$balance = UserBalance::where('user_id', Auth::id())->first();
View()->share('balance', $balance->balance);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.