0

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

1 Answer 1

1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.