Laravel Checking If a Record Exists

03/27/2020 03:00:01

I am new to Laravel. Please excuse the newbie question but how do I find if a record exists?

$user = User::where('email', '=', Input::get('email'));

What can I do here to see if $user has a record?

Verified Answer (530 Votes)

11/24/2014 03:31:24

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}
530

Answer #2 (24 Votes)

02/22/2016 23:35:48

One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.

24

Answer #3 (17 Votes)

12/21/2017 17:44:14
if (User::where('email', Input::get('email'))->exists()) {
    // exists
}
17
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.