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

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 day ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago