Back

Custom 500 Page for firstorfail() ModelNotFoundException


Can anybody explain step by step how to setup files to render a custom 500 page after a firstorfail() call in Laravel 5?

To stick to the documenation after this firstorfail results in a fail request:

$model = User::where('votes', '>', 100)->firstOrFail();

Where do I have to place this code? Inside the Controller?

use Illuminate\Database\Eloquent\ModelNotFoundException;

App::error(function(ModelNotFoundException $e)
{
   return Response::make('Not Found', 404);
});
kkiernan replied 4 years ago

I'm also curious about this. Here is a quick workaround in the meantime.

$model = User:where('votes', '>', 100)->first();

if (!$model)
{
    abort(500);
}

And then just create a file named 500.blade.php in the resources/views/errors directory. Laravel takes care of the rest. Check out the HTTP Exceptions section of the documentation.

dnixx replied 4 years ago Solution

In addition to creating resources/views/errors/500.blade.php, you can catch the ModelNotFoundException in app/Exceptions/Handler.php:

use Illuminate\Database\Eloquent\ModelNotFoundException;
// ...
public function render($request, Exception $e)
{
    if($e instanceOf ModelNotFoundException)
    {
        abort(500);
    }

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

(I'd do it with a 404 error.)

kkiernan replied 4 years ago

That does the trick!


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us