Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Sessions on 404 route

This is driving me crazy for weeks now: How can I make sessions available on the 404 page? I just embed the 404 error page in my default template. It also shows the navbar and the footer but how can I keep my user logged in when on a 404?

On a 404 Auth::check() always returns false and every else whats session specific is null or empty.

How to enable sessions on (404) error pages?

like image 204
festie Avatar asked May 10 '16 14:05

festie


3 Answers

What you can do is, inside the app/http/Kernel.php add the follwing block of code:

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

Inside the $middleware variable. So it would look like:

    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 as well.

like image 147
Kevuno Avatar answered Nov 19 '22 10:11

Kevuno


So I know this is an old question but in case anyone finds it useful here's how I've dealt with this:

In my App/Exceptions/Handler.php I changed the default render method to:

public function render($request, Exception $exception) {        
    \Route::any(request()->path(), function () use ($exception, $request) {
        return parent::render($request, $exception);
    })->middleware('web');
    return app()->make(Kernel::class)->handle($request);
}

This achieves 2 requirements:

  1. All the web middleware run correctly for the request
  2. Valid API routes do not start the session

This is in practice a decision to make the web middleware group the default to run when there's an error. Laravel would normally not run any middleware group on error pages. You can of course specify additional middleware or other route parameters if you want or use other conditions like e.g. if the path starts with api/ then use the api middleware instead making it more consistent.

Hopefully this is helpful to someone.

like image 5
apokryfos Avatar answered Nov 19 '22 11:11

apokryfos


For Laravel 5.5.5 or above just use the Route::fallback:

Route::fallback('PagesController@notFound');

this will help you to customize your 404 views having access to all the session, and more, stuff.

like image 3
Francisco Daniel Avatar answered Nov 19 '22 10:11

Francisco Daniel