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

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


try {
    $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
    // Do stuff when user exists.
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.


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

Leave a Comment