
本文旨在解决在使用 darryldecode/laravelshoppingcart 购物车包时,更新购物车中已存在商品数量的问题。通过修改 rowId 的生成方式以及更新逻辑,确保相同商品不会重复添加到购物车,而是正确更新其数量,并限制数量不超过库存。
在使用 Laravel 8 结合 darryldecode/laravelshoppingcart 购物车包时,可能会遇到更新购物车中商品数量的问题,特别是当用户多次点击“添加到购物车”按钮时。 默认情况下,如果购物车中已经存在某个商品,再次添加该商品时,期望的行为是更新该商品的数量,而不是添加一个新的相同商品。以下提供一种解决方案,以确保购物车中的商品数量得到正确更新,并限制数量不超过库存。
解决方案
关键在于使用商品ID作为购物车项目的 rowId。这样,当尝试添加已存在的商品时,购物车包会识别到该商品,并更新其数量,而不是添加一个新的项目。
修改 store 方法如下:
public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id; // 使用商品ID作为 rowId
$userID = $validated['user_id'];
$currentCart = \Cart::session($userID);
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $product->minStock($validated['quantity']),
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
$currentCartContents = $currentCart->get($rowId);
$quantity = $product->minStock($currentCartContents->quantity);
if($currentCartContents->quantity !== $quantity) {
$currentCart->update($rowId, [
'quantity' => [
'relative' => false,
'value' => $quantity,
]
]);
}
return redirect()->back();
}代码解释:
注意事项:
总结:
通过使用商品ID作为购物车项目的 rowId,可以有效地解决购物车商品数量更新的问题。 这种方法可以确保相同商品不会重复添加到购物车,而是正确更新其数量,并且通过minStock方法限制商品数量不超过库存,从而保证了数据的准确性和一致性。
以上就是使用 Laravel Shopping Cart 实现商品数量更新的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号