Eloquent ->first() if ->exists()

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?

188225 次浏览

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.

(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.

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

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());
}

Try it this way in a simple manner it will work

$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";