【发布时间】: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