ModelNotFoundException (404)
Thrown when a requested model instance cannot be found in the database.
Explanation
Laravel's ModelNotFoundException occurs when you use Eloquent methods likefindOrFail() or route model binding and the requested record doesn't exist in the database. By default, Laravel converts this exception into a 404 HTTP response. This is a common error during development when testing with IDs that don't exist or when records have been deleted. It can also happen in production when URLs reference stale or deleted resources.
Common Causes
- Record was deleted or never existed
- Incorrect ID passed in URL
- Stale cache referencing old IDs
- Migration not run or data not seeded
- Route model binding parameter mismatch
Solution
Use try-catch blocks around findOrFail() calls if you need custom error handling. Verify the record exists in the database by running a query or checking the database directly. Ensure route parameters match the expected type (e.g., integer IDs vs UUIDs). If using route model binding, confirm the route parameter name matches the variable name. For API responses, return a structured 404 JSON response with a meaningful message.
Code Example
// This throws ModelNotFoundException if user doesn't exist
$user = User::findOrFail($id);
// Custom handling with try-catch
try {
$user = User::findOrFail($id);
return view('users.show', compact('user'));
} catch (ModelNotFoundException $e) {
abort(404, 'User not found');
}
// Or use find() with manual check
$user = User::find($id);
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
Error Information
Language
php
Framework
laravel
Difficulty
Beginner
Views
142
Related Errors
PHP
Allowed Memory Size Exhausted
A script tried to allocate more memory than the allowed memory limit.
Laravel
ReflectionException
A class or method could not be found or instantiated via PHP reflection.
429
Backend
Rate Limit Exceeded (429)
Too many requests were sent in a given amount of time.
PHP
Cannot Use String Offset as Array
The code tries to access a string using array syntax, treating it as an array.