How to Use findOrFail in Eloquent: Laravel Quick Guide
Use
findOrFail in Eloquent to fetch a model by its primary key and automatically throw a ModelNotFoundException if no record exists. This method helps handle missing data gracefully by stopping execution and showing a 404 error.Syntax
The findOrFail method is called on an Eloquent model and takes a single argument: the primary key value you want to find. If the model exists, it returns the model instance; if not, it throws an exception.
- Model::findOrFail($id): Finds a model by its ID or fails.
php
User::findOrFail($id);
Example
This example shows how to use findOrFail to get a user by ID. If the user does not exist, Laravel automatically throws a 404 error, which you can catch or let Laravel handle.
php
<?php use App\Models\User; try { $user = User::findOrFail(1); echo 'User found: ' . $user->name; } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) { echo 'User not found!'; }
Output
User found: John Doe
Common Pitfalls
Common mistakes when using findOrFail include:
- Not handling the
ModelNotFoundException, which causes a server error if the model is missing. - Using
findOrFailwhen you expect multiple records; it only works for single primary key lookups. - Confusing
findOrFailwithfirstOrFail, which works with query conditions.
php
<?php // Wrong: expecting multiple results $users = User::findOrFail([1, 2, 3]); // Throws error // Right: use where + firstOrFail for conditions $user = User::where('email', 'test@example.com')->firstOrFail();
Quick Reference
| Method | Description |
|---|---|
| findOrFail($id) | Finds a model by primary key or throws ModelNotFoundException |
| firstOrFail() | Finds the first model matching query or throws ModelNotFoundException |
| find($id) | Finds a model by primary key or returns null if not found |
| first() | Finds the first model matching query or returns null |
Key Takeaways
Use findOrFail to get a model by ID and automatically handle missing records with an exception.
Always catch ModelNotFoundException or let Laravel show a 404 error page.
findOrFail works only with primary key lookups, not multiple IDs or complex queries.
Use firstOrFail for queries with conditions instead of findOrFail.
Proper error handling improves user experience by showing clear 'not found' messages.