Ensure only one single record is returned by Eloquent query
I checked Laravel collection methods and can't understand - is there a method for Eloquent query to ensure that exactly 1 record is returned - not 0 and not more than 1?
Something like singleOrFail().
As an example, in Entity Framework there is First() which works like Laravel's firstOrFail() and there is also Single().
Example #1.
There is 1 employee with 'salary' = 1000 in the database.
Employee::where('salary', 1000)->firstOrFail() will return this employee.
Example #2.
There are 2 employees with 'salary' = 1000 in the database.
Employee::where('salary', 1000)->firstOrFail() will return one of them.
Example #3.
There are no employees with 'salary' = 1000 in the database.
In this case Employee::where('salary', 1000)->firstOrFail() will raise an exception.
The idea of method I'm talking about (singleOrFail()) is that it will raise an exception not only in example #3 (because there are no matching users), but also in example #2 (because there are many matching users).
Just to close off this six-year-old thread, the method being saught here is sole().
$query->sole() will return exactly one record. If no records match, an exception will be thrown. If more than one record matches, also an exception will be thrown.