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

PhpLaravelEloquent

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

Try it this way in a simple manner it will work

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

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPositivityView Question on Stackoverflow
Solution 1 - PhpMatt BurrowView Answer on Stackoverflow
Solution 2 - PhpAshView Answer on Stackoverflow
Solution 3 - PhpJarek TkaczykView Answer on Stackoverflow
Solution 4 - PhpRashi GoyalView Answer on Stackoverflow
Solution 5 - Phpuser1669496View Answer on Stackoverflow