简体   繁体   English

更新购物车Laravel

[英]Updating shopping cart Laravel

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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