Laravel 8更新购物车中的产品(如果存在)



我使用Laravel 8与darryldecode/laravelshoppingcart车包。我有点挣扎与更新产品数量,如果它存在于用户的购物车。例如:如果购物车是空的,在添加产品时,然后多次点击"添加到购物车"。它只添加一种产品,然后将数量更新到最大值。但是当我添加第二个产品,然后再次添加产品1时,它会向购物车添加另一个产品。它绝对不应该添加另一种产品,但必须限制在第一种产品的最大数量。

我的购物车存储方法:

public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = uniqid();
$userID = $validated['user_id'];
// get current user cart
$currentCart = Cart::session($userID);
if(!empty($currentCart->getContent()->toArray())) {
foreach($currentCart->getContent() as $item) {
$productID = $item->associatedModel->id;
if($productID === $product->id) {
$currentCart->update($item->id, [
'quantity' => [
'relative' => false,
'value' => $product->minStock($item->quantity + $validated['quantity']),
]
]);
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
}
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
return redirect()->back();
}

我希望有人有类似的问题,知道如何解决这个问题。

好的,那么解决方案是使用产品ID作为$rowId,

$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id;
$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();

最新更新