Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

isadma's avatar

Laravel ModelNotFoundException and NotFoundHttpException

Controller:

$customer = Customer::findOrFail($id);

Handler.php

$this->renderable(function ( Exception $exception, $request) {
    if ($request->wantsJson()){
        dd([
            $exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException,
            $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
        ]);
     }
});

Output:

array:2 [
  0 => false
  1 => true
]

Why is ModelNotFoundException false? Please, share if you have any idea?

0 likes
4 replies
tykus's avatar

Because the prepareException method of the Illuminate\Foundation\Exceptions\Handler class converts the ModelNotFoundException to a NotFoundHttpException:

        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
isadma's avatar

I understood. Now how can I get ModelNotFoundException?

isadma's avatar
isadma
OP
Best Answer
Level 2

Solution:

if ($exception instanceof NotFoundHttpException) {
    if ($exception->getPrevious() && $exception->getPrevious() instanceof ModelNotFoundException){
        //do something
    }
}
5 likes

Please or to participate in this conversation.