1

Why still duplicate the data even i use the updateorcreate method in laravel sorry for my bad english here's my code:

$customerId = Auth::id();
    $unpaid = 'unpaid';
    $cartTables = CartModel::where(['user_id' => $customerId, 'cart_status' => $unpaid])->get();

$addReward = array();
    foreach( $cartTables as $key => $value) {
        $addReward[] = $request['product_id'][$key];
    }   

$datas = $request->product_id;

 if(count($cartTables) == 0 || $addReward != $datas) {
            foreach ($request->product_id as $key => $value) {
                $cartData = array(                 
                    'user_id' => $customerId,
                    'product_id' => $request['product_id'][$key],
                    'product_image' => $request['product_image'][$key],
                    'product_name' => $request['product_name'][$key],
                    'product_quantity' => $request['product_quantity'][$key],
                    'product_price' => $request['product_price'][$key],
                    'cart_created_at' => new DateTime(),
                    'cart_status' => 'unpaid',
                    
                );  
                CartModel::updateOrCreate($cartData);
            }  
    return redirect('product/cart');
}

I just want to insert only the unique products and ovewrite if have an existing products.

1 Answers1

0

updateOrCreate method takes two arrays as an argument: 1st: which model to update 2nd: with what data the model should be updated.

In your case, if you want to update a specific ID, your code should look something like this (for example, not sure what condition should be met):

CartModel::updateOrCreate(['product_id' => $productId], $cartData);

OR

CartModel::updateOrCreate(['user_id' => $customerId], $cartData);

Please read the documentation, it explains everything very clearly:

https://laravel.com/docs/8.x/eloquent#upserts

Fireflies
  • 67
  • 5