[php] Laravel Checking If a Record Exists

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?

This question is related to php laravel laravel-5 eloquent conditional

The answer is


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";

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


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


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

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

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.');
        }

    }

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

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!


here is a link to something l think can assist https://laraveldaily.com/dont-check-record-exists-methods-orcreate-ornew/


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';
    }


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 
}

$user = User::where('email', request('email')->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');

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

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}

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!');
}

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

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

But you use these ways also:

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->isEmpty())
{
  // object exists
} else {
  // object not found
}

4:

$user = User::where('email',  $request->email)->firstOrCreate([
      'email' => 'email'
],$request->all());

if($user->isEmpty()){
    // has no records
}

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


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


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

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


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.


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.


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

if(User::where('id', $user_id )->exists()){ // your code... }


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

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

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user doesn't exist!
    }

$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif

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 laravel-5

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Can't install laravel installer via composer Including a css file in a blade template? No Application Encryption Key Has Been Specified How to Install Font Awesome in Laravel Mix Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes Laravel 5.4 redirection to custom url after login How to set the default value of an attribute on a Laravel model laravel 5.3 new Auth::routes()

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

Examples related to conditional

Pandas/Python: Set value of one column based on value in another column Run an Ansible task only when the variable contains a specific string (Excel) Conditional Formatting based on Adjacent Cell Value Laravel Checking If a Record Exists Multiple conditions in if statement shell script The condition has length > 1 and only the first element will be used Creating a new column based on if-elif-else condition How to conditional format based on multiple specific text in Excel Using SUMIFS with multiple AND OR conditions Replacing Numpy elements if condition is met