Checking whether same product exists in cart-Magento 2

If the a products contains many attributes other than Qty , adding the same product to cart again will collapases and mismatches the attributes of the product.

To avoid or modify the situation we can check the same product already exists in the cart.

Is can be done in the controller of add to cart.

Required repository and constructors :-

public function __construct(
\Magento\Quote\Api\CartRepositoryInterface                   $quoteRepository
\Magento\Checkout\Model\Session                              $checkoutSession


parent::__construct($context);
$this->checkoutSession = $checkoutSession;
$this->quoteRepository = $quoteRepository;

public function execute()

if($this->checkoutSession->getQuote()->hasProductId($id)) {
    // code to execute when the product is already in the cart
}
else{
     // Product is not existed in the cart
}


Leave a comment

Your email address will not be published. Required fields are marked *