Laravel auth() component not available on error views

Viewed 43
  • Framework: Laravel 9.x

I'm attempting to use custom error pages. These are located in the default location: /resources/views/errors/....

These load as expected. However, they extend the base view template. This template uses the auth()->user() functionality to make decisions on visible menus.

The auth()->user() does not work on the error views. Note that it works as expected on other views.

How do I load the authenticated user for these error file views?

Thanks in advance.

1 Answers

Add this at the end of your route file for 404 error. Usually 404 doesn't get the session.

Route::fallback(function () {
    return abort(404);
});

All other errors such as 401, 403, 419, 429, 500, 503 these gets the session by default you do not need to do anything for that. Basically 404 means you do not have that route so system kicks user out of the system, in that case kernel does not load with all providers. if provider do not load you will not get session. So for 404 we are telling our system let our user stay but if the page is not available use fallback route.

If you want to test it for each errors you can do something like this.

  • Create a blank route
Route::get('/blank', fn() => abort(401));
  • go to 401.blade.php change message to auth()->user()->id.
  • visit the /blank URL.

If you see your id your session is working.

Related