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
143
Related Errors
PHP
Parse Error: Syntax Error
PHP detected a syntax error in the source code that prevents parsing.
PHP
Type Error: Return Type Must Be Compatible
A method override has a return type that conflicts with the parent class or interface.
Database
Access Denied for User
The database rejected the connection because the username or password is incorrect.
Database
Lock Wait Timeout Exceeded
A database query waited too long for a lock held by another transaction.