Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Checking If a Record Exists

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?

like image 770
Ben Avatar asked Nov 23 '14 22:11

Ben


People also ask

How to check if record already exists in Laravel?

$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. Show activity on this post.

How do I know if a table is empty in laravel?

You can call eloquent count function to get count and then check if count is equal to zero. if($collection->isEmpty()){ //products table is empty. }

IS NOT NULL laravel?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


1 Answers

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 } 
like image 176
lukasgeiter Avatar answered Nov 23 '22 23:11

lukasgeiter