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
You can do, if it exists, Update. If not, Add. (Basic concept of update or create)
if you need to duplicated data cause you need to update one element
you can use
sync()
method like :-sync()
mean if exit will update it, or will be create new record