I want to get the first row in table where condition matches:
User::where('mobile', Input::get('mobile'))->first()
It works well, but if the condition doesn't match, it throws an Exception:
ErrorException
Trying to get property of non-object
Currently I resolve it like this:
if (User::where('mobile', Input::get('mobile'))->exists()) {
$user = User::where('mobile', Input::get('mobile'))->first()
}
Can I do this without running two queries?
(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:
Oh, also:
count()
instead ifexists
but this could be something used afterget
.An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.
get
returnsCollection
and is rather supposed to fetch multiple rows.count
is a generic way of checking the result:Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.
The correct way to user first() and check for a result:
Other techniques (not recommended, unnecessary overhead):
or
or
Each one is a different way to get your required result.