Search code examples
laravellaravel-10laravel-middleware

How to return a 404 status and view from Laravel middleware


I'm building an admin section for a Laravel 10 app using the boilerplate Breeze routes and templates (for now) and I have a group of prefixed routes that I want to return a 404 error for in the following cases:

  1. there is NO signed in user
  2. if there IS a signed in user, they are not an admin

In other words, the ONLY time the prefixed routes should produce anything substantial is if the authenticated user is an admin. Otherwise, I want it to appear as the routes don't even exist.

I am at my wits end trying to return the 404 error view and status code from the middleware. I have been tinkering with the code and reading documentation for HOURS now to no avail, and yet I get the feeling the answer is right in front of me but I'm missing something.

This is code I have in the web.php routes file:

Route::prefix('admin')->middleware(['admin'])->group(function() {
    Route::get('/', [AdminDashboardController::class, 'index'])->name('admin');
});

And here's what I have in the handle() function for the admin middleware:

public function handle(Request $request, Closure $next): Response
{
    if ($request->user() === null || $request->user()->role !== 'admin') {
        return response('This page cannot be found', 404, []);
    }
    
    return $next($request);
}

This code works just fine. BUT, I want to return the 404 page and HTTP 404 status code rather than a plain text page with the response message. If I try to return anything EXCEPT the above it just seems to skip right on to the next bit of middleware. As in, it attempts to render the Breeze dashboard component as if the user was signed in, even though the user isn't signed in.

Could anybody please guide me on how I can return the 404 error page and status code in place of the current response above?


Solution

  • public function handle(Request $request, Closure $next): Response
    {
        if ($request->user() === null || $request->user()->role !== 'admin') {
            //remove this return response('This page cannot be found', 404, []);
            abort(404); // replace this
        }
        
        return $next($request);
    }
    

    And here reference for design your own 404 error handling page https://magecomp.com/blog/create-custom-error-page-laravel-10/