Home > Software engineering >  update multiple data if exists, create if does not exist in laravel
update multiple data if exists, create if does not exist in laravel

Time:03-31

I want to insert or update multiple rows. if some data already exists then it will update otherwise it will create new items. My code from are :

foreach ($product_id as $key => $value) {
    $input['product_name'] = $request->product_name[$key];
    $input['product_price'] = $request->product_price[$key];

    $add_product = Product::upsert($input,'product_name');
}

I am not getting any error, Its just inserting all data instead of updating the existing items.

CodePudding user response:

use updateOrCreate if product_name column is not primary key or unique key in database

foreach ($product_id as $key => $value) {
        $input['product_name'] = $request->product_name[$key];
        $input['product_price'] = $request->product_price[$key];
    
        $add_product = Product::updateOrCreate(['product_name'=>$request->product_name[$key]], $input);
}

if column product_name is unique or primary key then

$data=[]; 

    foreach ($product_id as $key => $value) {
        $data[$key]['product_name'] = $request->product_name[$key];
        $data[$key]['product_price'] = $request->product_price[$key]; 
    } 
    $add_product = Product::upsert($data,['product_name']);

As per doc

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

Ref:https://laravel.com/docs/9.x/eloquent#upserts

CodePudding user response:

You can use the function ::firstOrCreate($data) for this, it returns the item when found or the inserted item when there could not be an item found with the inserted data. You can find it here: https://laravel.com/docs/9.x/eloquent#retrieving-or-creating-models

foreach ($product_id as $key => $value) {
    $input['product_name'] = $request->product_name[$key];
    $input['product_price'] = $request->product_price[$key];

    $add_product = Product::firstOrCreate($input);
}

What I would do when you need to update multiple products instead of just one is checking the count of the product with the specific information. After this I would update it when the count is higher than 1.

foreach ($product_id as $key => $value) {
    $input['product_name'] = $request->product_name[$key];
    $input['product_price'] = $request->product_price[$key];

    $productCount = Product::where('product_name', $request->product_name[$key])->count();

    if ($productCount > 1) {
      $products = Product::where('product_name', $request->product_name[$key])->get();
      $products->update($input);
    } else {
      $add_product = Product::firstOrCreate($input);
    }
}

Disclaimer: I did not test the code.

  • Related