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