laravel - Accessing Auth in Exceptions\Handler.php -


i'm trying access auth class within render method of app\exceptions\handler class (app/exceptions/handler.php) determine if user logged in, using auth::check() method.

this worked fine in 5.1, i've upgraded 5.2 , no longer works.

to debug this, i've been printing auth::user() logs (which returns null), returning redirect() view.

then view/controller redirect goes to, printing same auth::user() logs, works expected , returns logged in user.

so seems there's no problem accessing auth class or user() method within exceptions\handler class, it's returns null reason, whereas other parts of app return user..

thanks info on this!

this happens because startsession middleware inside $middlewaregroups (the application's route middleware groups), don't have access authenticated user because middlewares initialize session starts later in lifecycle exceptionhandler.

in app\kernel.php file, move line:

 \illuminate\session\middleware\startsession::class, 

from $middlewaregroups global stack $middleware. these middleware run during every request application so, after this, auth::user() works.


warning: solution not able use cookie session driver. works file , others.


update:

if still need use startsession inside global stack $middleware , need cookie session driver, must move 3 middlewares $middlewaregroup $middleware in next order:

\app\http\middleware\encryptcookies::class, \illuminate\cookie\middleware\addqueuedcookiestoresponse::class, \illuminate\session\middleware\startsession::class 

Comments