php
framework_laravel
ai_generated
true
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\User] 42
ID: php/laravel-model-not-found
93%Fix Rate
93%Confidence
70Evidence
2023-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 11 | active | — | — | — |
Root Cause
ModelNotFoundException is thrown by Laravel when using findOrFail(), firstOrFail(), or route model binding and the record does not exist. This is expected behavior for missing records but often surfaces as an unhandled 404 error in production.
genericWorkarounds
-
94% success Handle the exception properly in the exception handler with a user-friendly 404 response
In app/Exceptions/Handler.php (or bootstrap/app.php for Laravel 11), register a handler for ModelNotFoundException that returns a proper 404 JSON response for API routes or renders a 404 view for web routes. Laravel's default handler already converts this to a 404 but customize the message.
-
90% success Use optional route model binding or add existence validation before queries
For route model binding, use Optional binding by defining a 'missing' method on the route. For manual queries, use 'exists()' check before findOrFail, or use find() with explicit null handling: '$user = User::find($id); if (!$user) { return response()->json(["error" => "Not found"], 404); }'.
Dead Ends
Common approaches that don't work:
-
Catching ModelNotFoundException globally and returning an empty model
70% fail
Returning an empty model instead of a 404 hides the fact that the resource does not exist. Downstream code may attempt to use null properties from the empty model, causing confusing errors or displaying incorrect data to users.
-
Replacing all findOrFail() calls with find() to avoid the exception
68% fail
Using find() instead of findOrFail() returns null when the record is missing, which pushes null handling to every call site. This leads to 'call to member function on null' errors scattered throughout the codebase.
Error Chain
Preceded by:
Frequently confused with: