与所有视图共享数据


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行错误:试图获得非对象属性

line 23 : view()->share('balance', $balance->balance);

MENU USER SECTION(在所有视图的布局中):

@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

谢谢你的帮助!

这可能不是最好的答案,但是您考虑过将结果存储在会话中吗?

会话可以被任何视图检查和读取。

if ($request->session()->has('balance')) {
     $request->session()->get('balance', 0);
}

检查用户是否登录。如果用户未认证,则不存在Auth::user()->id,还需要检查$balance。如果查询返回null,则显示错误。

AppServiceProvider.php第23行错误:试图获得非对象属性

试试这个:

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之前执行的。因此,它不会检索会话id。您可以使用此代码。因为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);
            });
        }