Home > OS >  How to prevent duplicates entries in for each loop when inserting in laravel? - Laravel 8
How to prevent duplicates entries in for each loop when inserting in laravel? - Laravel 8

Time:01-10

I have a function in controller which fetches all products based on Auth::id:

    $products = DB::table('products')
              ->where('created_by_id', Auth::id())
              ->get();

Then has a for each loop as follows which inserts and update:

    foreach($products as $key => $product){
                        $previous_product = Product::create((array) $product);
                        $previous_product->save();
                        $previous_product->update(['created_by_id' => $reseller_id->reseller_id]);
                }

Which work perfectly, but the problem I am facing is products are duplicated twice instead of duplicated once. as shown on below image:

enter image description here

What I have tried to do is to use replicate() method instead of create() but I got null on replicate and the problem still persists.

Any help given to resolve my issue will be greatly appreciated.

CodePudding user response:

Try to use insertOrIgnore method with query builder It will fix your issue.

  DB::table('products')->insertOrIgnore($arrayOfProducts);

CodePudding user response:

I would give replicate another shot:

$products = Product::where('created_by_id', Auth::id())->get();

foreach ($products as $product) {
    $product->replicate()
        ->fill(['created_by_id' => $reseller_id->reseller_id])
        ->save();
}

The code you have doesn't appear that it would cause 2 new records to be inserted, though the save call you have is unneeded since create creates the record (saves it) and update calls save.

  •  Tags:  
  • Related