Laravel 5.0 custom 404 does not use middleware

2019-07-09 02:12发布

问题:

I'm using a middleware to parse the output of the templates. This is working fine for all pages.

However when I want to show a 404 (got a custom page for that) it doesn't treat it as a http request (that's what I think) since it doesn't go through the middleware.

My question is, how to have ALL requests go through the middleware.

回答1:

The error pages don't go through the routes.php.

In Kernel.php move your middleware from the $routeMiddleware array to $middleware array.

Middleware in this array will run on every request (tested in 5.1).



回答2:

At Laravel 5.4 and probably some older ones you can modify the file app/exceptions/Handler.php and the function render like this:

if( is_a( $exception, \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class ) ) {
    return redirect()->route( 'error_404' );
}

// ... old code in the function ...

in this way every 404 errors are redirected to certain real route that acts like other routes of site.

You may also submit any data from current request to show a reasonable error at the target.