2017-01-10 131 views
1

我想在AppserviceProvider中訪問Authenticated user id它的工作正常,當我在應用程序中意味着一旦登錄其工作正常,但是當我註銷它給出錯誤而不是去到登錄頁面錯誤試圖獲取非對象的屬性(laravel 5.3)

試圖讓非對象

這是我寫的引導方法Appserviceprovider的代碼的性能。

public function boot() 
{ 
    view()->composer('*', function($view){ 
    $view->with('user', Auth::user()); 

    $counter = DB::table('notifications')->where('notifications.userid', Auth::user()->id)->count(); 
    View::share('counter', $counter); 
    }); 

它會給我上面的查詢where子句時出錯,當我註銷。其原因後註銷其無法得到auth用戶ID .. 請幫助我如何解決或如何做到這一點的最好的方式,如果任何

+0

當你註銷'Auth :: user() - > id'時,問題出在這裏'Auth :: user()'是空的 – Beginner

回答

0

你應該看看這個Laravel protecting routes

可以保護路由所以當你沒有登錄時它們不會被訪問。這應該解決你的問題。

如果您希望此路線在您未登錄時可訪問,則應在查詢周圍設置if語句。您可以使用Auth::check(),看看用戶是否登錄。

if(Auth::check()) { 
    //Do stuff 
} 
0

爲了避免這種情況,當你退出,因爲Auth::user()爲空只需使用一個三元條件

如果Auth::user()然後用Auth::user()->id否則,如果不使用null值,而不是

Auth::user() ? Auth::user()->id : null 

改變這一行

$counter = DB::table('notifications')->where('user_notifications.user_id', Auth::user() ? Auth::user()->id : null)->count(); 
+0

親愛的它仍然存在同樣的錯誤 –

+0

@recoverymen你能var_dump(Auth :: user());'看到它的結果,如果你註銷 – Beginner

+0

結果是什麼?你可以顯示它 – Beginner

0

我覺得你的代碼需要更新,如:

public function boot() 
{ 
    if(Auth::user()){ 
     view()->composer('*', function($view){ 
     $view->with('user', Auth::user()); 

     $counter = DB::table('notifications')->where('user_notifications.user_id', Auth::user()->id)->count(); 
     View::share('counter', $counter); 
     }); 
    } 

希望這對你的工作!

+0

它仍然給出相同的錯誤..我不能使用檢查方法的開始,因爲'$ view-> with('user',Auth :: user());' 給我訪問權限 –

相關問題