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.
Currently available for 2-3 new projects
About Hafiz
Full Stack Developer from Italy. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.
View Portfolio