Laravel Checking If a Record Exists
Asked Answered
I

33

409

I am new to Laravel. 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?

Insomuch answered 23/11, 2014 at 22:24 Comment(5)
Well to start you need to execute a findOrFail() or similar on the $user querySaccule
that doesn't really helpInsomuch
Then what does it do? Why doesn't it help? $user = User::where('email', '=', Input::get('email')); simply creates a query in $user, you need to execute that query. findOrFail() is one way of executing that query. get() would be another way, firstOrFail() anotherSaccule
If a suggestion "doesn't really help" try saying why it doesn't really help, because that way it means we know how to improve/change that suggestionSaccule
consider this i.imgur.com/ulqyOiw.png no need to reinvent the wheelDomineca
S
846

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
}
September answered 23/11, 2014 at 22:31 Comment(15)
if you call exists() against a non existent record then it gives error: Call to a member function exists() on nullGailey
@Gailey You are doing something wrong. You can't call exists after you've already ran the querySeptember
@September guess you are right. I had already called first()Gailey
I used to use -> $email_exists = DB::table('users')->select('email')->where('email', $request->email)->count(); but your method is better :)Isotope
alternatively, if (!User::where('email', '=', Input::get('email'))->exists())... could workSitton
I think this is the better way to find if User is exists. User::where('email', '=', 'value')->count() > 0;Recollection
@JanakaPushpakumara That alone has sometimes caused me error. I also add && isset()Caddoan
exists() might be a good option too but I feel like it is not the most optimised way, is it?Bouley
@Gailey i just tested ->exists() with laravel 5.5, it says false if it doesn't exist.Brentwood
FYI, you can leave out the '=' value: User::where('email', Input::get('email'))->exists();Impasse
Why making SQL to continue counting rows with count after it has already found one? Exists is more appropriate here - it stops right after finding one match. Even if performance difference might be negligible, still it expresses the intention better.Frail
What if you want to check for multiple row exist?Rankle
@Brentwood Same here with laravel 7.xSilver
in laravel 8.x ;exists() returns false if no row found.so it is safe to use.Bullhead
Not working with milliseconds case. Is there any way to fix this?Lustrate
L
85
if (User::where('email', Input::get('email'))->exists()) {
    // exists
}
Loadstar answered 21/12, 2017 at 12:44 Comment(1)
This should be the accepted answer. The most efficient and dedicated way to do it is through the exists() method.Curzon
F
47

In laravel eloquent, has default exists() method, refer followed example.

if (User::where('id', $user_id )->exists()) {
    // your code...
}
Facies answered 11/8, 2019 at 6:23 Comment(0)
S
32

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

Scottscotti answered 22/2, 2016 at 18:35 Comment(2)
while not fitting the question, still, very useful functions. the difference between the two is that firstOrNew instantiates an instance of the model called while firstOrCreate saves the queried model instantly so you need to update changes on the firstOrCreate'd model.Indivisible
Yep, or another way of thinking of it is, use firstOrCreate if you can pass all the attributes in one go (use the second parameter), but firstOrNew if you're going to need further logic before saving.Gastropod
R
20
if($user->isEmpty()){
    // has no records
}

Eloquent uses collections. See the following link: https://laravel.com/docs/5.4/eloquent-collections

Ramadan answered 25/7, 2017 at 3:17 Comment(2)
Yeah but its not returning a collection. It's returning a single model object as you would assume each user has a unique email so ->isEmpty() will throw an error.Dedie
And what if I get the following error: Call to a member function isEmpty() on nullCaddoan
K
13

Laravel 5.6.26v

to find the existing record through primary key ( email or id )

    $user = DB::table('users')->where('email',$email)->first();

then

      if(!$user){
             //user is not found 
      }
      if($user){
             // user found 
      }

include " use DB " and table name user become plural using the above query like user to users

Kino answered 11/7, 2018 at 7:7 Comment(0)
W
12

It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.

$result = User::find($email)->exists();

If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e

Call to a member function exists() on null.

But the case is different for where() thing.

$result = User::where("email", $email)->exists();

The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.

Wardle answered 5/4, 2022 at 20:8 Comment(0)
P
9
if (User::where('email', '[email protected]')->first()) {
    // It exists
} else {
    // It does not exist
}

Use first(), not count() if you only need to check for existence.

first() is faster because it checks for a single match whereas count() counts all matches.

Pomiferous answered 15/2, 2019 at 5:39 Comment(0)
S
9

This will check if requested email exist in the user table:

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}
Submiss answered 25/3, 2019 at 9:50 Comment(0)
R
3

In your Controller

$this->validate($request, [
        'email' => 'required|unique:user|email',
    ]); 

In your View - Display Already Exist Message

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
Rencontre answered 11/5, 2017 at 7:29 Comment(0)
E
3

I solved this, using empty() function:

$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
    User::destroy($user->id);
Euxenite answered 11/3, 2021 at 7:39 Comment(0)
H
2
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
Hinkle answered 4/7, 2017 at 12:14 Comment(0)
A
2

Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.

if ( User::find( $userId ) === null ) {

    return "user does not exist";
}
else {
    $user = User::find( $userId );

    return $user;
}

It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.

Amphibolite answered 9/7, 2018 at 4:4 Comment(1)
You could replace find with where. User::where(id, 1)->first()Germano
M
2
if ($u = User::where('email', '=', $value)->first())
{
   // do something with $u
   return 'exists';
} else {
  return 'nope';
}

would work with try/catch

->get() would still return an empty array

Melaniemelanin answered 23/1, 2019 at 9:54 Comment(0)
M
2
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Mutism answered 7/8, 2019 at 4:20 Comment(0)
S
2

Simple, comfortable and understandable with Validator

class CustomerController extends Controller
{
    public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'phone' => 'required|string|max:255|unique:customers',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }
Salamander answered 28/6, 2020 at 10:30 Comment(0)
M
2

you have seen plenty of solution, but magical checking syntax can be like,

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.

Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models

Militarist answered 12/10, 2021 at 10:27 Comment(0)
J
1

This will check if particular email address exist in the table:

if (isset(User::where('email', Input::get('email'))->value('email')))
{
    // Input::get('email') exist in the table 
}
Jim answered 31/12, 2017 at 20:27 Comment(0)
R
1

Shortest working options:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
Regressive answered 30/9, 2018 at 1:58 Comment(0)
F
1
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

can be written as

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

This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.

Feder answered 16/10, 2018 at 19:35 Comment(0)
H
1

I think below way is the simplest way to achieving same :

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user exist!
    }else{
       // user does not exist
    }
Hijoung answered 23/1, 2019 at 12:17 Comment(0)
R
0

You can use laravel validation if you want to insert a unique record:

$validated = $request->validate([
    'title' => 'required|unique:usersTable,emailAddress|max:255',
]);

But also you can use these ways:

1:

if (User::where('email',  $request->email)->exists())
{
  // object exists
} else {
  // object not found
}

2:

$user = User::where('email',  $request->email)->first();

if ($user)
{
  // object exists
} else {
  // object not found
}

3:

$user = User::where('email',  $request->email)->first();

if ($user->isNotEmpty())
{
  // object exists
} else {
  // object not found
}

4:

$user = User::where('email',  $request->email)->firstOrCreate([
      'email' => 'email'
],$request->all());
Robomb answered 31/10, 2017 at 13:8 Comment(2)
Please consider that count method counts records and it is not good performance-wise in this scenario.Respondent
@Respondent I did not use count methodRobomb
M
0

Created below method (for myself) to check if the given record id exists on Db table or not.

private function isModelRecordExist($model, $recordId)
{
    if (!$recordId) return false;

    $count = $model->where(['id' => $recordId])->count();

    return $count ? true : false;
}

// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);

Home It helps!

Murine answered 23/1, 2019 at 19:19 Comment(1)
Note that by using count, you are counting a certain record throughout the table. While the exists method returns true if the table contains at least one desired record.Respondent
B
0

The Easiest Way to do

    public function update(Request $request, $id)
{


    $coupon = Coupon::where('name','=',$request->name)->first(); 

    if($coupon->id != $id){
        $validatedData = $request->validate([
            'discount' => 'required',   
            'name' => 'required|unique:coupons|max:255',      
        ]);
    }


    $requestData = $request->all();
    $coupon = Coupon::findOrFail($id);
    $coupon->update($requestData);
    return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Bow answered 31/12, 2019 at 6:58 Comment(0)
S
0

Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)

 public function store(Request $request)
    {

        $target = DB:: table('categories')
                ->where('title', $request->name)
                ->get()->first();
        if ($target === null) { // do what ever you need to do
            $cat = new Category();
            $cat->title = $request->input('name');
            $cat->parent_id = $request->input('parent_id');
            $cat->user_id=auth()->user()->id;
            $cat->save();
            return redirect(route('cats.app'))->with('success', 'App created successfully.');

        }else{ // match found 
            return redirect(route('cats.app'))->with('error', 'App already exists.');
        }

    }
Shiv answered 1/2, 2020 at 13:50 Comment(0)
O
0

If you want to insert a record in the database if a record with the same email not exists then you can do as follows:

$user = User::updateOrCreate(
    ['email' => Input::get('email')],
    ['first_name' => 'Test', 'last_name' => 'Test']
);

The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.

You can check out the docs here: Laravel upserts doc

Olinger answered 19/5, 2021 at 8:41 Comment(0)
S
0
$userCnt     = User::where("id",1)->count();
if( $userCnt ==0 ){
     //////////record not exists 
}else{
      //////////record exists 
}

Note :: Where condition according your requirements.

Slough answered 6/10, 2021 at 11:3 Comment(0)
M
0
  1. Simply use this one to get true or false

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

  2. if you want $user with result you can use this one,

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

and check result like this,

if(count($user)>0){}
  1. Other wise you can use like this one,

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

    if($user->exists()){ $user = $user->get(); }

Moody answered 27/7, 2022 at 3:20 Comment(0)
F
0

You can try this for a boolean result as true or false

$columns = [
    'email' => "[email protected]",
];
$exists = User::exists($columns);

if($exists)
     ...some code
Foresail answered 24/2, 2023 at 21:4 Comment(0)
S
-1

The efficient way to check if the record exists you must use is_null method to check against the query.

The code below might be helpful:

$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
 //user does not exist...
}else{
 //user exists...
}
Swinge answered 9/2, 2020 at 22:9 Comment(0)
R
-1

In Controller :

            public function validation(Request $request)
            {
            $email= $request->input('email');

            if (DB::table('customer')->where('email','=',$email)->exists())
            {
                echo 'EXIST';
            } else {
                echo 'DOESNT EXIST';
            }}

HTML form :

<input id="email" name="email" type="email" placeholder="Email">

Route :

Route::post('/login', [LoginController::class,'validation']);
Rollin answered 10/8, 2023 at 4:12 Comment(0)
S
-4

It's simple to get to know if there are any records or not

$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
Sinuosity answered 14/3, 2017 at 10:47 Comment(1)
Fetching all records, then counting?!Respondent
C
-15

this is simple code to check email is exist or not in database


    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }

Cotsen answered 29/3, 2017 at 11:17 Comment(1)
If you have a table User with ...say over1,000,000,000 records, you'll be checking for a veeeeeeery long timeDrift

© 2022 - 2025 — McMap. All rights reserved.