laravelshoppingcart icon indicating copy to clipboard operation
laravelshoppingcart copied to clipboard

Same item with different attributes

Open debuEkodus opened this issue 4 years ago • 5 comments

How to add same item id with different attributes? Suppose an item has attributes black and blue.

debuEkodus avatar Oct 28 '20 09:10 debuEkodus

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; }

muratenes avatar Nov 13 '20 14:11 muratenes

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?

debuEkodus avatar Nov 18 '20 12:11 debuEkodus

You can add this function anywhere like Trait. Then you can call the basket id wherever you need it

muratenes avatar Nov 20 '20 14:11 muratenes

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

omaresmael avatar Dec 20 '20 17:12 omaresmael

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 ] );

ac00perw avatar Apr 30 '21 16:04 ac00perw