Cart – How to Check if Product is Already in Cart in Magento 2.2

addtocartcartmagento2.2

I am creating certain group of products which has one quantity for each product. So, I want to disable the Add to Cart button if that same product is in cart and change the text of the button to Already in Cart.
How can I achieve this??
I am using magento 2.2

Any help/suggestion is appreciated.
Thank you.

Best Answer

You can use like this in list.phtml:-

$cart = $objectManager->get('\Magento\Checkout\Model\Session')->getQuote();
$result = $cart->getAllVisibleItems();
$itemsIds = array();
foreach ($result as $cartItem) {
    array_push($itemsIds, $cartItem->getProduct()->getId());
}

print_r(in_array($productId, $itemsIds));

As an alternative you can also use Magento default feature:-

For individual settings, go to product details

Click Advanced Inventory

Maximum allowed inventory, and make it 1

Related Topic