A good use case for the Eloquent sole() method

The sole() method has been around for a while, but I don't use it very much. Here's one place I found it useful.

Joel Clermont
Joel Clermont
2023-09-21

As part of writing a one-time user import command, I needed to look up a company record by name. This is the company all the users would be associated with.

When I first wrote the code, it looked like this:

$clientId = Client::where('name', 'Some Name Here')->firstOrFail()->id;

During code review, Aaron pointed out the sole() method would be a better choice. By using firstOrFail(), I was already acknowledging the fact that if we couldn't find a company with this name, the command should fail.

Thinking about it more, if it had instead found two client records with the same name, that would be an equally unexpected situation, and the command should also fail.

This is a perfect use case for sole(). It will throw an exception in both cases: either finding no records, or finding more than one matching record. The revised code looks like this:

$clientId = Client::where('name', 'Some Name Here')->sole()->id;

For places where you're using firstOrFail() in your code, it's worth considering if you would you ever be concerned if Eloquent returned more than one record? If so, sole() is the method you want.

Here to help,

Joel

P.S. Ever wonder if your Laravel app could be more secure? Download our free book for 7 steps to review.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.