I'm having a problem trying to update the total quantity of items which are in my shopping cart. The problem that I'm having is when I update the quantity of an item, it takes that quantity as the total quantity. How can I sum the quantities of my items in the shopping cart? And then get the total quantity.
This is my controller
public function cartUpdate(Request $request, $id) {
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$quantity = $request->quantity;
$product = Product::find($id);
$cart->updateItem($product, $id, $quantity);
Session::put('cart', $cart);
return response()->json(['success' => true]);
}
My cart model
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart)
{
if ($oldCart)
{
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function updateItem($item, $id, $quantity) {
$this->items[$id]['qty'] = $quantity;
$this->items[$id]['price'] = $quantity * $item->price;
$this->totalQty = $this->items[$id]['qty'];
$this->totalPrice = $this->totalQty * $item->price;
}
If somebody needs the code. I did it. This is going to work when you need to update your items quantity
public function updateItem($item, $id, $quantity) {
$this->items[$id]['qty'] = $quantity;
$this->items[$id]['price'] = $quantity * $item->price;
$this->totalQty = 0;
foreach($this->items as $element) {
$this->totalQty += $element['qty'];
$this->totalPrice = $this->totalQty * $item->price;
}
}