简体   繁体   中英

Change value multidimensional array in session Laravel

I have a shopping cart and I want to update the amount of it in the cart session.

This is my cart session:

array:1 [▼
  1 => array:6 [▼
    "name" => "Carocroc Lam"
    "image" => "carocroc_lam_15kg.jpg"
    "price" => 45.95
    "unit" => 15
    "name_unit" => "kg"
    "amount" => "2"
  ]
]

So I know that I need a foreach to update the item in the shopping cart but when I do that and send it back to the request it only put in the amount of the item.

What I want to receive is that only the amount will be updated and send the whole updated array back tot the shopping cart.

I hope someone can help me out.

So, say you save the cart array as $cartItems , you can do:

foreach ($cartItems as $cartItem) {
  $cartItem['amount'] = NEWAMOUNTVALUE;
}

If you need further help please clarify in the comments!

$cartItems = new Collection();
foreach ($items as $item) {
    $cartItem = new CartItem();
    $cartItem->amount = $item['amount'];
    $cartItem->save();
    $cartItems.push($cartItem);
}

return $cartItems;

If you want to store it in a collection and return it properly you can use this code. If you want to edit the array directly and then do the update you can use the above code from @party-ring with a bit of extra information below.

foreach ($cartItems as &$cartItem) {
  $cartItem['amount'] = NEWAMOUNTVALUE;
  CartItem::update($cartItem);
}

return $cartItems;

I found the solution by myself I did the following and it worked.

foreach ($currentCart as $item){
  $currentCart[1] = [
      'name' => $item['name'],
      'image' => $item['image'],
      'price' => $item['price'],
      'unit' => $item['unit'],
      'name_unit' => $item['name_unit'],
      'amount' => $item['amount'] = $request->input('amount'),
  ];
  $request->session()->put('cart', $currentCart);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM