【问题标题】:Updating shopping cart Laravel更新购物车 Laravel
【发布时间】:2018-12-28 00:44:06
【问题描述】:

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

这是我的控制器

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

【问题讨论】:

    标签: php laravel-5.5


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多