簡體   English   中英

Laravel 5.2-與所有視圖共享數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM