Magento – Allow only one qty of item into cart in Magento 2

addtocartcontrollersmagento2product

I have created a custom controller in my module and calling via ajax to add the item to cart.

Below is my controller code.

<?php 

 namespace {Vendor}\{Module}\Controller\Product;                           
 class AddProduct extends \Magento\Framework\App\Action\Action                 
{
 protected $formKey;
 protected $cart;
 protected $product;
 protected $checkoutSession;
 public function __construct(
 \Magento\Framework\App\Action\Context $context,
 \Magento\Framework\Data\Form\FormKey $formKey,
 \Magento\Checkout\Model\Cart $cart,
 \Magento\Catalog\Model\ProductFactory $product,
 \Magento\Checkout\Model\Session $checkoutSession,
 array $data = []) {
  $this->formKey = $formKey;
  $this->cart = $cart;
  $this->product = $product;
  $this->checkoutSession = $checkoutSession;
  parent::__construct($context);
  }
  public function execute()
  {
  $productId = 1;
  $customPrice = 150;
  $params = array(
    'form_key' => $this->formKey->getFormKey(),
    'product_id' => $productId, //product Id
    'qty'   => 1 //quantity of product
  );
  $_product = $this->product->create()->load($productId);
  $this->cart->addProduct($_product, $params);

  $productItem = $this->getProductQuote($_product);
  $productItem->setCustomPrice($customPrice);
  $productItem->setOriginalCustomPrice($customPrice);
  //Enable super mode on the product.
  $productItem->getProduct()->setIsSuperMode(true);
  $this->cart->save();
  echo "success";
 }


 public function getProductQuote($product)
 {
  $quote = $this->checkoutSession->getQuote();
  $cartItems = $quote->getItemByProduct($product);
  return $cartItems;
 } 
}

The above code adds the product of qty 1 to the cart with a custom price whenever it is called.

I want to add only 1 qty of product to the cart. suppose if its called two or three times, only one qty should be present in cart. Need to remove previously added qty from the cart.

Is something can be done programmatically? There is a product setting in backend "Maximum qty allowed in cart", we can set this value but I am looking for the code how it can be done programmatically.

Can anyone look into it and help me, please. Thanks

Best Answer

You can use getItemByProduct

If Item is exist -> use addProduct function -> else -> use updateItem function

$item = $this->cart->getQuote()->getItemByProduct($_product);
if ($item) {
    $this->cart->addProduct($_product, $params);
} else {
    $this->cart->updateItem($item->getId(), 1);
}