0

I have added some products in cart pragmatically when i Iterate on quote it iterates but on each iteration it is giving same product data

 $quote = $this->quoteRepository->get( $quote->getId() );
 foreach ( $quote->getAllItems() as $item ) {
    if ( $item->getProductId() == $productId ) {
                    return true;
       }
 }

Please suggest some solution what's the issue here

1 Answer 1

0

it appears that you're using $quote->getAllItems() to loop through the items in the quote. This method will return all items in the quote, including both parent and child items. In the case of configurable and bundle products, this can lead to duplicates.

To resolve this issue, you should use $quote->getAllVisibleItems() instead, which will return only the parent items, excluding duplicates:

$quote = $this->quoteRepository->get($quote->getId());
foreach ($quote->getAllVisibleItems() as $item) {
    if ($item->getProductId() == $productId) {
        return true;
    }
}

By using $quote->getAllVisibleItems(), you should get the expected result without encountering the same product data on each iteration.

If you still face the same issue after making this change, please double-check that you're adding products to the cart correctly and not inadvertently adding the same product multiple times. Additionally, ensure that you're using the most recent version of Magento 2, as it may contain bug fixes or improvements that resolve the issue.

1
  • I tried getAllVisibleItems also it wont't work and i only have virtual products on my site which i am creating programaticlly and the adding it to cart Apr 17 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.