Laravel 5.0 custom 404 does not use middleware

2019-07-09 02:34发布

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.

2条回答
地球回转人心会变
2楼-- · 2019-07-09 02:43

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).

Image showing middleware and a 404 page

查看更多
Evening l夕情丶
3楼-- · 2019-07-09 02:50

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.

查看更多
登录 后发表回答