正在更新购物车 Laravel

Updating shopping cart Laravel

我在尝试更新购物车中的商品总数时遇到问题。我遇到的问题是当我更新一个项目的数量时,它将那个数量作为总数量。 如何汇总购物车中的商品数量?然后得到总数量。

这是我的控制器

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]);

}

我的购物车型号

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;
}

如果有人需要代码。我做到了。当您需要更新商品数量时,这将起作用

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;
    }
}