Eloquent ->first() if ->exists()
(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
.
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:
$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
// Do stuff if it doesn't exist.
}
Other techniques (not recommended, unnecessary overhead):
$user = User::where('mobile', Input::get('mobile'))->get();
if (!$user->isEmpty()){
$firstUser = $user->first()
}
or
try {
$user = User::where('mobile', Input::get('mobile'))->firstOrFail();
// Do stuff when user exists.
} catch (ErrorException $e) {
// Do stuff if it doesn't exist.
}
or
// Use either one of the below.
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection
if (count($users)){
// Use the collection, to get the first item use $users->first().
// Use the model if you used ->first();
}
Each one is a different way to get your required result.
Try it this way in a simple manner it will work
$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";
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