0

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

3
  • 1
    you may get some idea from this. ( the cart is in session there ). stackoverflow.com/questions/69977302/… Commented Nov 18, 2021 at 3:31
  • @DebasisRath ah! thanks, It works for me. I just need to change the session to cookies Commented Nov 18, 2021 at 4:24
  • Good to know Catto, 1 like for that answer would be encouraging for me :) Commented Nov 18, 2021 at 7:03

2 Answers 2

1

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

Comments

1

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

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.