Access Auth in Exceptions \ Handler.php

I am trying to access a class Authfrom the class rendering method App\Exceptions\Handler(app / Exceptions / Handler.php) to determine if the user is currently using the method Auth::check().

This worked fine in 5.1, but I upgraded to 5.2 and no longer works.

To debug this, I typed Auth::user()in the logs (which returns NULL) and then returns the redirect () to another view.

Then it is redirected from the view / controller, printing the same Auth::user()in the logs, which works as expected and returns the registered user.

Thus, it seems that there is no problem accessing the Auth class or using the user () method from the class Exceptions\Handler, it simply returns NULL for some reason, while other parts of the application return the user.

Thanks for any info on this!

+4
source share
2 answers

This is because the middleware StartSessionis inside $middlewareGroups(the middleware groups of the application), so you do not have access to the authenticated user, because the intermediaries that initialize your session start later in the life cycle than ExceptionHandler.

In the file, app\Kernel.phpmove this line:

 \Illuminate\Session\Middleware\StartSession::class,

$middlewareGroups $middleware. , Auth::user() .


: cookie. file .


UPDATE:

StartSession $middleware, cookie session driver, $middlewareGroup $middleware :

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class
+4

, , 404 . 500, Auth:: user(). , routes.php

Route::any('{page}', 'ErrorController@Error404')->where('page', '(.*)');

. ErrorController @Error404 Auth. , App\Exceptions\Handler, ErrorController@Error404. ( : - , .)

+3

Source: https://habr.com/ru/post/1625754/


All Articles