Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 830
Positivity Avatar asked Jul 02 '14 12:07

Positivity


People also ask

What is first () in eloquent?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.

What does First () return in laravel?

It just returns null.

How do you use order by in eloquent?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.


2 Answers

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.

like image 64
Matt Burrow Avatar answered Oct 02 '22 13:10

Matt Burrow


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

like image 27
Ash Avatar answered Oct 02 '22 15:10

Ash