Reputation: 10451
I'm having a problem in accessing the Auth::user() in my route.php. So far here's what i've got:
Route::group(['middleware' => 'auth'], function () {
if(Auth::user()->role == "manager"){
Route::get('/','ManagerController@index');
}
else if(Auth::user()->role == "rater"){
Route::get('/','RaterController@index');
}
});
It gives me this error "Trying to get property of non-object" whenever I try to use the Auth::user()->role
Upvotes: 1
Views: 11857
Reputation: 2023
Change your code to:
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');
}
}
});
Because if the current user has not logged in yet, he will not have a role
so Auth::user()
will return null
and thus accessing role
property is not possible. You need to check first if the user is logged in by using if (Auth::check())
.
P.S. Checking the authentication inside the routes file is such a bad practice and should be handled inside a controller
. Hope this helps.
Upvotes: 5