[php] 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?

This question is related to php laravel eloquent

The answer is


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


Try it this way in a simple manner it will work

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

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

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()