Reputation: 183
I have a cart session in laravel that looks like below:
{
"5c10d896edd57": {
"quantity": "3",
"price": "20.0",
"dishId": "39508",
},
"5c10d8b55f34e": {
"quantity": "3",
"price": "389.0",
"dishId": "39510",
}
}
I want to update the quantity if same dishId is added again for this I have wrote this code
$previous_cartData = session('cart');
if(!empty($previous_cartData)){
foreach ($previous_cartData as $key => $p_cart) {
if($p_cart->dishId == $cart->dishId){
$update_cart['quantity']= $p_cart->dishId+$cart->quantity;
$request->session()->put('cart.'.$key, $update_cart);
}else{
$request->session()->put('cart.'.uniqid(), $cart);
}
}
}
But unfortunately it replaces the whole object like this:
{
"5c10d896edd57": {
"quantity": "4"
},
"5c10d8b55f34e": {
"quantity": "3",
"price": "389.0",
"dishId": "39510",
}
}
I only want to update the quantity without changing other keys
Upvotes: 0
Views: 336
Reputation: 162
Thats because $update_cart
doesn't hold any other values but 'quantity'.
Try something like this:
$previous_cartData = session('cart');
if(!empty($previous_cartData)){
foreach ($previous_cartData as $key => $p_cart) {
if($p_cart->dishId == $cart->dishId){
$update_cart = $p_cart;
$update_cart['quantity']= $p_cart->dishId+$cart->quantity;
$request->session()->put('cart.'.$key, $update_cart);
}else{
$request->session()->put('cart.'.uniqid(), $cart);
}
}
}
Upvotes: 1