Laravel 5: Sessions on 404 routes

This drives me crazy for a few weeks: How can I make sessions available on page 404? I just paste the 404 error page into my default template. It also shows the navigation bar and footer, but how can I keep my user logged in when at 404?

At 404, Auth :: check () always returns false, and all other values ​​for the session are zero or empty.

How to enable sessions on error pages (404)?

+3
php session laravel
source share
2 answers

What you can do is add the following code inside app / http / Kernel.php:

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

Inside the $ middleware variable. So it will look like this:

  protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; 

It worked for me, I hope it works for you too.

+5
source share

Just to expand the existing answer a bit: be sure to remove this middleware from $ middlewareGroups, if you have one, so you don't use middleware twice.

You end up with something like this:

 protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, //\Illuminate\Session\Middleware\StartSession::class, //\Illuminate\Session\Middleware\AuthenticateSession::class, //\Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; 

As far as I understand, this was due to the fact that the session-related middleware, while in a web group, was applied only to those pages that were redirected to web.php. And since error handling is not redirected to the routed page by default, we did not have access to the session.

Thus, the middleware will apply to all pages, not just the routes on the web page, including errors.

I initially found soution here , but it took me a while to figure out why this was happening (I thought I caught a cold, ruined everything, feel free to confirm or fix this, please).

Hope this helps, it works for me on Laravel 5.4

+1
source share

All Articles