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?
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.
It just returns null.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With