
本文旨在解决在使用 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();
}
登录后复制
代码解释:
- $rowId = $product->id;: 将商品ID赋值给 $rowId。这确保了每个商品在购物车中都有一个唯一的ID。
- $currentCart->add(…): 使用 $rowId 将商品添加到购物车。如果购物车中已经存在具有相同 $rowId 的商品,add 方法会更新该商品的数量。$product->minStock($validated[‘quantity’]) 用于限制添加到购物车的数量不超过库存。
- $currentCartContents = $currentCart->get($rowId);: 获取购物车中该商品的信息。
- $quantity = $product->minStock($currentCartContents->quantity);: 再次使用 $product->minStock() 确保购物车中的数量不超过库存。
- if($currentCartContents->quantity !== $quantity): 比较购物车中原有的数量和经过库存限制后的数量,如果数量不一致,则更新购物车中的数量。
注意事项:
- 确保 Product 模型中存在 minStock() 方法,该方法用于限制添加到购物车的数量不超过库存。
- CartStoreRequest 验证器应包含对 product_id 和 quantity 的验证规则。
- 根据实际需求调整代码中的价格、图片等属性。
总结:
通过使用商品ID作为购物车项目的 rowId,可以有效地解决购物车商品数量更新的问题。 这种方法可以确保相同商品不会重复添加到购物车,而是正确更新其数量,并且通过minStock方法限制商品数量不超过库存,从而保证了数据的准确性和一致性。
以上就是使用 Laravel Shopping Cart 实现商品数量更新的详细内容,更多请关注php中文网其它相关文章!