I'm building a Laravel app where the main layout (layouts.app
) is used across all pages.
However, I include the header (which contains the user dropdown based on Auth::user()
) via a separate @include('header')
in each view and not inside the layout itself.
Now, when a user is logged in and they visit a non-existent URL (which triggers a 404
), Laravel renders the errors.404
view.
@if (Auth::user())
<li class="">
<a href="{{ route('profile') }}">
<i class="fa fa-user-circle"></i> Profile
</a>
</li>
@else
<li class="">
<a href="{{ route('login') }}" class="btn btn-primary text-white">
<i class="fa fa-user-circle"></i> Sign In
</a>
</li>
@endif
What you observe is because the middleware is not loaded globally by default.
The rationale is to load as little as necessary.
For example, if there is an error with the workflow of your application's middleware and the error page must be displayed, and then this is already the request to display the error page, even the error page would be broken.
You can configure your application the middleware to load globally and then you have the side-effects of them with every request.
However, for your use-case of your 404 error page handling, IMHO the fallback route offers more fine-grained control: https://laravel.com/docs/12.x/routing#fallback-routes
As the documentation for Fallback Routes outlines, you can add all the middleware you'd like to use to it, and it is then with the API you're likely already comfortable with from routing in general.