Eloquent
Laravel 8
Laravel 9
Laravel 10
Laravel 11
Laravel 12
Model Not Found Exception in Laravel - Solutions
This exception is thrown when using findOrFail() or firstOrFail() and no matching record exists in the database.
The Error
Error Message
ModelNotFoundException - No query results for model
Common Causes
- 1 Record with given ID doesn't exist
- 2 Using findOrFail with non-existent ID
- 3 Route model binding with invalid parameter
- 4 Soft deleted record being accessed
Solutions
1
Use find() instead of findOrFail() for optional records
PHP
$post = Post::find($id);
if (!$post) {
return redirect()->back()->with('error', 'Post not found');
}
2
Handle the exception gracefully
PHP
try {
$post = Post::findOrFail($id);
} catch (ModelNotFoundException $e) {
abort(404, 'Post not found');
}
3
Include soft deleted records if needed
PHP
$post = Post::withTrashed()->findOrFail($id);
Need Help With Your Laravel Project?
I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.
About Hafiz
Senior Full Stack Developer. I build production software with Laravel, Filament, Vue, and AI integrations, and write about the real decisions behind shipping it.
Get in touch →