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,
P.S. Ever wonder if your Laravel app could be more secure? Download our free book for 7 steps to review.