I'm trying to create add to cart function, and the product is stored inside an array. The array is like this:
array:2 [▼
0 => array:2 [▼
"product_id" => "Produk-0036"
"quantity" => "2"
]
1 => array:2 [▼
"product_id" => "Produk-0037"
"quantity" => "3"
]
]
My question is how to update the quantity if product_id already exist inside the array?
$get_cart = Cookie::get('user_cart');
if(isset($get_cart)) {
$cart_array[] = json_decode($get_cart);
}
$cart_array[] = ["product_id" => $request->product_id, "quantity" => $request->quantity];
$cart_json = json_encode($cart_array);
$cart_cookies = Cookie::forever('user_cart', $cart_json);
Using the code above will add new index in the array instead of updating the quantity of already exist product
Thanks
CodePudding user response:
I think you need update product quantity before Cookie::forever.
You can refer my suggest:
$cart_array = [
["product_id" => "Produk-0036", "quantity" => 2],
["product_id" => "Produk-0037", "quantity" => 3],
];
foreach($cart_array as &$cart)
{
if(isset($cart["product_id"]) && $cart["product_id"] == $request->product_id)
{
$cart["quantity"] = $request->quantity;
}
}
$cart_json = json_encode($cart_array);
$cart_cookies = Cookie::forever('user_cart', $cart_json);
CodePudding user response:
You may use array_map() function
Try something like this:
$cart_array = [
[
"product_id" => "Produk-0036",
"quantity" => "2"
],
[
"product_id" => "Produk-0037",
"quantity" => "3"
]
];
$product_id = "Produk-0036"; // product_id to update
$cart_array = array_map(function ($item) use ($product_id) {
if ($item["product_id"] == $product_id) {
$item["quantity"] = "5"; // update quantity
}
return $item;
}, $cart_array);
var_dump($cart_array); // OUTPUT: updated array