簡體   English   中英

在route.php中訪問Auth :: user()

[英]Access Auth::user() in route.php

我在route.php中訪問Auth :: user()時遇到問題。 到目前為止,這是我所擁有的:

Route::group(['middleware' => 'auth'], function () {
    if(Auth::user()->role == "manager"){
        Route::get('/','ManagerController@index');
    }
    else if(Auth::user()->role == "rater"){
        Route::get('/','RaterController@index');
    }
});

每當我嘗試使用Auth :: user()-> role時,都會出現此錯誤“試圖獲取非對象的屬性”

將您的代碼更改為:

Route::group(['middleware' => 'auth'], function () {
            if (Auth::check()) {
                if(Auth::user()->role == "manager"){
                    Route::get('/','ManagerController@index');
                }
                else if(Auth::user()->role == "rater"){
                    Route::get('/','RaterController@index');
                }
            }
        });

因為如果當前用戶尚未登錄,那么他將沒有role因此Auth::user()將返回null ,因此無法訪問role屬性。 您需要先使用if (Auth::check())用戶是否登錄。

PS檢查路由文件中的身份驗證是一種不良做法,應在controller內部處理。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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