How To

How to Prevent Adding Same Product to Cart more than One time in Magento 2

Hello Magento Friends,

Hope all are healthy, wealthy, and safe. Today I am going to throw light on How to Prevent Adding Same Product to Cart more than One time in Magento 2.

Many times it may happen that the user actually needs a single quantity but mistakenly adds the same product more than once to the cart. This leads to unnecessary product buying. To avoid this, Magento 2 store owners can prevent customers to add the same product to the cart more than one time. If the user needs an additional quantity, he/she needs to go to My Cart and change the quantity of the product accordingly.

If the user tries to add the already added product to the cart, it shows the message, “Item already in cart. If you need to change quantity please go to my cart.”

Let’s find out the steps, How to Prevent Adding Same Product to Cart more than One time in Magento 2.

Steps to Prevent Adding Same Product to Cart more than One time in Magento 2:

Step 1: First, go to the below path

app\code\Vendor\Extension\etc\di.xml

And add the code as follows

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Checkout\Model\Cart">
      <plugin disabled="false" name="Vendor_Extension_Plugin_Magento_Checkout_Cart_BeforeAddToCartProduct"     type="Vendor\Extension\Plugin\Magento\Checkout\Cart\BeforeAddToCartProduct"/>
 </type>
</config>

Step 2: Now, move to the below path

app\code\Vendor\Extension\Plugin\Magento\Checkout\Cart\BeforeAddToCart.php

And add the below-mentioned code

<?php
    declare(strict_types=1);
    
namespace Vendor\Extension\Plugin\Magento\Checkout\Cart;

use Magento\Checkout\Model\Cart;
use Magento\Checkout\Model\Session;
use Magento\Catalog\Model\Product;
use Magento\Checkout\Model\Session\Proxy as SessionProxy;
use Magento\Framework\Message\ManagerInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\UrlInterface;

class BeforeAddToCartProduct
{

    private $messageManager;
    private $cartSession;
    private $configurableProduct;
    private $url;
    private $session;

    public function __construct(
        Configurable $configurableProduct,
        ManagerInterface $messageManager,
        SessionProxy $cartSession,
        UrlInterface $url,
        Session $session)
   {
        $this->messageManager = $messageManager;
        $this->cartSession = $cartSession;
        $this->configurableProduct = $configurableProduct;
        $this->url = $url;
        $this->session = $session;
    }

    public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo=null)
    {
        $enableProductCartControl=true;

        $product = null;
        $parentProduct=null;

        if ($productInfo instanceof Product)
        {
            $product = $productInfo;
            if (!$product->getId())
            {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __("This product wasn't found. Verify the product and try again.")
                );
            }
        }

        if ($product)
        {
            // For Simple Product
            if ($product->getTypeId()==='configurable')
            {
                if (isset($requestInfo['super_attribute']))
                {
                    $parentProduct=$product;
                    $childProduct = $this->configurableProduct->getProductByAttributes($requestInfo['super_attribute'] ,$product);
                    // change $product to child
                    $product=$childProduct;
                }
            }
            if ($product && $enableProductCartControl)
            {
                    // For check product is in cart or not
                    if($this->cartSession->getQuote()->hasProductId($product->getId()))
                    {
                        // Redirection to the cart page
                        $this->session->setRedirectUrl($this->url->getUrl('checkout/cart/index'));
                        throw new \Magento\Framework\Exception\LocalizedException(
                            __("[x] This product is already in the cart. Testing, testing : ". $product->getSku())
                        );
                    }
             }
        }
        return [$productInfo, $requestInfo];
    }

    /**
     * Get request for product add to cart procedure
     *
     * @param \Magento\Framework\DataObject|int|array $requestInfo
     * @return \Magento\Framework\DataObject
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    private function _getProductRequest($requestInfo)
    {
        if ($requestInfo instanceof \Magento\Framework\DataObject)
        {
            $request = $requestInfo;
        }
        elseif (is_numeric($requestInfo))
        {
            $request = new \Magento\Framework\DataObject(['qty' => $requestInfo]);
        }
        elseif (is_array($requestInfo))
        {
            $request = new \Magento\Framework\DataObject($requestInfo);
        }
        else
        {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('We found an invalid request for adding product to quote.')
            );
        }
        return $request;
    }
}

Conclusion:

Hence, with the above steps, you can Prevent Adding Same Product to Cart more than One time in Magento 2. Alternatively, you can even restrict your customer from adding the product to the cart in Magento 2.

Mention in the comment part, your difficulties, and queries. Do share the article with your Magento buddies. Stay connected, stay updated with the latest Magento news and solutions.

Happy Coding!

Click to rate this post!
[Total: 6 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago