Skip to content

Prevent selling the same item more than 1 time

I have a store which contains only downloadable products.

I’d like to prevent the same product from being added in quantities greater than 1 and remove the quantity field from everywhere (cart, minicart, etc).

I tried to use a Plugin in my module but it doesn’t work.

app/code/Vendor/Module/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        
    <!-- Frontend -->
    <type name="MagentoCheckoutModelCart">
        <plugin disabled="false" name="Vendor_Module_Plugin_Magento_Checkout_Cart_BeforeAddToCart" type="VendorModulePluginMagentoCheckoutCartBeforeAddToCart"/>
    </type>
</config>

app/code/Vendor/Module/Plugin/Magento/Checkout/Cart/BeforeAddToCart.php

<?php
declare(strict_types=1);

namespace VendorModulePluginMagentoCheckoutCart;
use MagentoCheckoutModelCart;
use MagentoCheckoutHelperCart as CartHelper;
use MagentoCatalogModelProduct;
use MagentoCheckoutModelSessionProxy as SessionProxy;
use MagentoFrameworkMessageManagerInterface;
use MagentoConfigurableProductModelProductTypeConfigurable;
use MagentoStoreModelStoreManagerInterface;
use MagentoCheckoutModelSession;
use MagentoFrameworkUrlInterface;

class BeforeAddToCart {

    public function beforeAddProduct(MagentoCheckoutModelCart $subject, $productInfo, $requestInfo=null){
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $session = $objectManager->create('MagentoCheckoutModelSession');
        
        $product_id = $requestInfo['product'];
        $quote = $session->getQuote()->hasProductId($product_id);
        if($quote){
                        // redirect to cart
                        $this->session->setRedirectUrl($this->url->getUrl('checkout/cart/index'));
                        throw new MagentoFrameworkExceptionLocalizedException(
                            __("[x] This product is already in the cart. Testing, testing : ". $product->getSku())
                        );
        }
        return [$productInfo, $requestInfo];

    }
}