Pradhumn Vaishnav
Pradhumn Vaishnav

Reputation: 37

Checking if record exists in Laravel not working

i'm doing this to check if the record exists with chasis_number. if it doesn't exist insert data and if it does don't insert. but it's not working.

        $chunks = $insert_data->chunk(500);
            
        $owner = Owner::where('chasis_number', '=', request()->get('chasis_number'))->first();
        foreach ($chunks as $chunk)
        {
        if ($owner === null) {
               Owner::insert($chunk->toArray());
          }
        }

Upvotes: 1

Views: 6918

Answers (2)

OMR
OMR

Reputation: 12188

Instead of using the first method to determine if any records exist that match your query's constraints, you may use the exists

$ownerExist = Owner::where('chasis_number', '=', request()->get('chasis_number'))->exists();

   if ($ownerExist== true) {
               Owner::insert($chunk->toArray());
          }

Upvotes: 1

Tanmay
Tanmay

Reputation: 3159

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument:

https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models

Upvotes: 2

Related Questions