Laravel Route model binding throws NotFoundHttpException instead of ModelNotFoundException

182 Views Asked by At

I am using route model binding for my API routes.

Route::middleware('client')->group(function(){
    Route::get('/documents/{document}', [DocumentController::class, 'get']);
    Route::apiResource('documents', DocumentController::class)->only('store', 'destroy');
    Route::post('filter', [DocumentController::class, 'filter']);
});

DocumentController:

public function get(Document $document): JsonResponse|string|null
{
    // do some stuff

    return response()->json([
        'code' => 404,
        "message" => "Some Message"
    ], 404);
}

When I access my API route (GET - /api/documents/$uuid) with valid $uuid that exist in DB everything works fine. But If I call it with invalid $uuid which doesn't exist in DB it throws exception:

"message": "No query results for model [App\\Models\\Document] some_uuid_here",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",

Problem is thrown exception is NotFoundHttpException while it should be ModelNotFoundException.

Shouldn't NotFoundHttpException need to get thrown if route completely undefined? I don't want to show user Route not defined while there is actual route but not record with given primary key.


I surrounded Document::findOrFail($value); in try catch block just to debug exception and even findOrFail throws NotFoundHttpException

try {
    Document::findOrFail($value);
}catch (\Exception $exception){
    throw $exception;
}

enter image description here

try {
    Document::findOrFail($value);
}catch (\Exception $exception){
    echo get_class($exception);
}

enter image description here

0

There are 0 best solutions below