skip to Main Content

I got this error

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2-7-8' for key 'cart_product_cart_id_product_id_price_id_unique' (SQL: insert into `cart_product` (`cart_id`, `created_at`, `price_id`, `product_id`, `quantity`, `updated_at`) values (2, 2023-01-09 12:23:57, 8, 7, 1, 2023-01-09 12:23:57))"

Code:

$cart_product = $cart->products()
    ->where('product_id', $product->id)
    ->where('price_id', $price->id)
    ->first();

if ($cart_product->structure == 'single') {
    $cart->products()->attach(array([
        'product_id' => $product->id,
        'quantity'   => $request->quantity,
        'price_id'   => $price->id
    ]));
}

How can add a row to table product_cart although it already exists ?

2

Answers


  1. You can do, if it exists, Update. If not, Add. (Basic concept of update or create)

    if ($cart_product->structure == 'single') {
        if ($cart->products()->where('product_id', $product->id)->where('price_id', $price->id)->exists()) {
            // Update
            $cart->products()->updateExistingPivot($product->id, [
                'quantity' => $request->quantity,
                'price_id' => $price->id
            ]);
        } else {
            // Insert
            $cart->products()->attach(array([
                'product_id' => $product->id,
                'quantity'   => $request->quantity,
                'price_id'   => $price->id
            ]));
        }
    }
    
    Login or Signup to reply.
  2. if you need to duplicated data cause you need to update one element

    you can use sync() method like :-

    
    $cart->products()->sync(array([
                    'product_id' => $product->id,
                    'quantity'   => $request->quantity,
                    'price_id'   => $price->id
                ]));
    

    sync() mean if exit will update it, or will be create new record

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search