Laravel 5 findOrFail ModelNotFoundException Show a 404 Error Page

This is a free resource from my online course, From Idea To Launch, where I teach you how to build a full Laravel web application, step by step, at beginner's speed. Learn more →

By default, when you use an Eloquent model’s findOrFail in a Laravel 5 application and it fails, it returns the following error:


ModelNotFoundException in Builder.php line 129:
No query results for model [App\Model].

But it’d be much more ideal if, instead, you could just display a “404 Page Not Found” page.

Well, you can, very easily.

Catch ModelNotFoundException exceptions when using findOrFail

Open up the app/Exceptions/Handler.php file, and add the code shown below to the top of the render function:


.
.
.
    public function render($request, Exception $e)
    {
        if ($e
            instanceof
            \Illuminate\Database\Eloquent\ModelNotFoundException) 
        {
          abort(404);
        }

        return parent::render($request, $e);
    }
.
.
.

And that code will work universally, when you call findOrFail on any of your Eloquent models.

So now, when findOrFail fails to find an object, you’ll receive the typical:


404 Not Found

There you go!