Search code examples
laravelauthenticationlaravel-routing

Auth::user() is null in new route


i'm using laravel 6 and have 2 route in my app; index and dashboard. My routes/web is:

Auth::routes();
Route::middleware(['auth'])->group(function () {
    Route::get('/index', 'todoApp\TodoController@index')->name('index');
    Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});

i added dashboard route recently. Auth::user() is null when i dump it in dashboard route but doesn't in index. What's the


Solution

  • Your Controller is instantiated before the middleware stack has ran; this is how Laravel can know what middleware you have set via the constructor. Because of this you will not have access to the authenticated user or sessions at this point. Ex:

    public function __construct()
    {
        $this->user = Auth::user(); // will always be null
    }
    

    If you need to assign such a variable or access this type of information you would need to use a controller middleware which will run in the stack after the StartSession middleware:

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // this is getting executed later after the other middleware has ran
            $this->user = Auth::user();
    
            return $next($request);
        });
    }
    

    When the dashboard method is called, the middleware stack has already passed the Request all the way through to the end of the stack so all the middleware needed for Auth to be functioning and available has already ran at that point which is why you have access to Auth::user() there.