laravelshoppingcart
laravelshoppingcart copied to clipboard
Same item with different attributes
How to add same item id with different attributes? Suppose an item has attributes black and blue.
i am facing same problem. i am resolved this problem with this way :
/** * generate custom Id for product * @param int $productID * @param array|null $selectedSubAttributesIdList * @return mixed|string */ public function getCartItemId(int $productID, ?array $selectedSubAttributesIdList) { return $selectedSubAttributesIdList ? $productID . '-' . implode('_', $selectedSubAttributesIdList) : $productID; }
i am facing same problem. i am resolved this problem with this way :
/**
- generate custom Id for product
- @param int $productID
- @param array|null $selectedSubAttributesIdList
- @return mixed|string */ public function getCartItemId(int $productID, ?array $selectedSubAttributesIdList) { return $selectedSubAttributesIdList ? $productID . '-' . implode('_', $selectedSubAttributesIdList) : $productID; }
Where do we need to add this function?
You can add this function anywhere like Trait. Then you can call the basket id wherever you need it
I had the same problem. I was attaching the rowId with the product id and so same attributes share product id will cause a problem So I changed it to a random number generated whenever I click on the add to cart button and send it with the data as rowId,
var productId = Math.floor(Math.random() * 1000);
data: { 'rowId': productId, 'name': $(this).data("name"), 'price': $(this).data("price"), 'quantity': $('#quantity').val(), 'associatedModel': $(this).data("associatedModel"), 'attr' : arr, }
and then attach this generated number to an attribute like data-id when displaying the content od the cart so that I can again update or remove that element
<h4><a data-id="'+theRandomGeneratedId+'" href="#">'+val['name']+'</a></h4>
I hope that helps, and if you figure out a better idea I will be glad to hear
Reviving this old open ticket. To solve this problem I create an md5 hash from the product ID and a serialized array of my attributes for the cart ID. That way products with matching attributes will update and others will add products to the cart.
$id = md5($product->id.serialize($options)); $item=Cart::add(['id' => $id, 'name' => $product->title, 'price' => $price, 'quantity' => 1, 'attributes' => $options ] );