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?
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.
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:
web
middleware run correctly for the requestThis 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With