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:
$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();
Oh, also: count()
instead if exists
but this could be something used after get
.
Try it this way in a simple manner it will work
$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";
An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.
try {
$user = User::where('mobile', Input::get('mobile'))->first();
} catch (ErrorException $e) {
// Do stuff here that you need to do if it doesn't exist.
return View::make('some.view')->with('msg', $e->getMessage());
}
get
returns Collection
and is rather supposed to fetch multiple rows.
count
is a generic way of checking the result:
$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user
// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users
Source: Stackoverflow.com