Handling 404 and other HTTP errors in Laravel 5

January 15, 2015

In Laravel 4, it was a little bit tricky to handle all the possible 404 cases in the app and return a nice customised error page. Thankfully Laravel 5 makes it a lot easier to return a specific view for any HTTP error.

If you take a look at app/Exceptions/Handler in the development branch of Laravel 5, you'll spot this code handling the response to an exception.

if ($this->isHttpException($e))
    return $this->renderHttpException($e);

This handly little bit of code leverages this HTTP handling in the framework which simply checks to see if the exception is a HTTP exception, and then if the corresponding view exists in the errors view folder. If the view does exist it returns it with the correct HTTP status.

if (view()->exists('errors.'.$e->getStatusCode()))
    return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode());

So, to handle a 404 with your own error page, simply create the view errors/404.blade.php. Likewise, if you want to handle another sort of error you can just create a view with the appropriate HTTP status code. You may even notice that the framework ships with a 503.blade.php, which is used when you pop your app into maintenance mode with php artisan down.

A blog about Laravel & Rails,
written by Dwight Watson.