When you expect exactly one matching record, use sole() instead of firstOrFail(). It guards against multiple records by throwing MultipleRecordsFoundException.
When querying unique records, firstOrFail() silently returns the first record even if multiple records match due to data integrity issues. sole() makes sure exactly one record exists.
// Throws ModelNotFoundException if 0, MultipleRecordsFoundException if 2+
$user = User::where('verification_token', $token)->sole();
- Asserts that exactly one record matches criteria
- Catches data integrity anomalies before bad states propagate
- Throws explicit MultipleRecordsFoundException
Related Tips
View all tips →Optimize Date Queries by Replacing whereYear() with whereBetween()
Replace whereYear() and whereMonth() on large database tables with whereBetween() date ranges to enable SQL index lookups.
Efficient Unique Slug Generation in Eloquent Without Looping Queries
Generate unique database slugs in Eloquent by querying the maximum existing numerical suffix directly instead of executing repeated queries in a while loop.