1

Magento 2.3.3

Store is strictly downloadable mp3 products. Thus max quantity for each product is one (adding more than one would not make sense). I'd like to check if a product is already in the cart, and if so, I'll hide the Add to Cart button.

(Current default behavior is that if the product is already in the cart, clicking the button sends you to the product page with an error message. I'd like to skip this.)

I've found this, but it doesn't work:

How to check whether a product is in the cart?

The $productInfo array in the above example is empty, even when there are items in the cart.

This also did not help me: how to check if product is already in cart

3
  • Where do you want to send the customer if the product already exist? It makes sense Magento sending to product page (where add to cart button was clicked) and show the error message. Dec 29, 2019 at 22:28
  • As I mentioned, I will hide the Add to Cart button. I'll replace it with text saying the product is already in the shopping cart.
    – Reviresco
    Dec 29, 2019 at 23:43
  • This should work in your case: magento.stackexchange.com/questions/209894/…. Dec 30, 2019 at 0:46

2 Answers 2

0

Try this -

use Magento\Checkout\Model\Session as CheckoutSession;

public function __construct(
    CheckoutSession $checkoutSession
) {
    $this->checkoutSession = $checkoutSession;
}

public function getProductData()
{
    $quote = $this->checkoutSession->getQuote();
    $item = $quote->getItemById($productId);
    if($item)
    {
      echo "Item available in cart";
    }
    else
    {
      echo "Item not available in cart";
    }
}

Here $productId is your product id.

2
  • It won't be working under Full Page Cache Dec 30, 2019 at 18:54
  • And why is that?
    – Nayem323
    Dec 31, 2019 at 4:38
0

Well, this issue I am also facing when enabling of FPC cart item not getting properly, So there is another way of getting the cart item is through phtml/js file inject the following code as your requirment ,

require('Magento_Customer/js/customer-data').get('cart')().items

You can also refer to this link hopefully it will help you allot How to get Cart items collection on Product view page?

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.