Sydney Loteria
Sydney Loteria

Reputation: 10451

Access Auth::user() in route.php

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

Answers (1)

Osama Sayed
Osama Sayed

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

Related Questions