In this episode, we take a look at the firstOrFail
method, which you might already know from Eloquent. The cool thing is, it's now available on the database query builder too!
We start by demoing how firstOrFail
works on an Eloquent model, using a user record as an example. We experiment with both existing and non-existing users to see how the method either returns the record or throws an exception that leads to a 404 response. This is super handy when you want to fetch something in a controller without wrapping things in endless if
statements or using helpers like abortIf
.
Next, we switch over to the regular DB query builder with the DB
facade—perfect for times when you're not using Eloquent models. Previously, you had to manually check if the result from first()
was null and handle the 404 yourself. But now, you can just use firstOrFail
and it will throw a 404 for you automatically.
One important note: the exceptions thrown are different. Eloquent's version throws a ModelNotFoundException
, while the DB query builder throws a generic RecordNotFoundException
. They both cause a 404 error, but if you're catching exceptions manually, you'll need to be aware of which one you're dealing with.
In short, firstOrFail
now gives you a cleaner and more consistent way to handle not-found records whether you're using Eloquent or the plain query builder.