How To

How to restrict your customer from adding the product to cart in Magento 2

Selling thousands of products in your eCommerce store, several times it happens that the store owner has to set some restrictions to prevent customers from ordering the products. Maybe the for limiting cart quantity or product is available for specific customer group or available during a flash, sale at that time they have to restrict customers adding the product to their shopping cart. And, you can’t find any option in Magento 2 backend to set such restrictions at that time custom extension development key is the only option to do the same.
Recently, we came across such a situation where the store owner wants to prevent their customer from adding store products if the cart quantity exceeds more than two. At that time, to restrict your customers from adding the product to cart in Magento 2 we make use of observer and here is the code for same.
Firstly, we need to create ‘event.xml’ file in our extension etc folder using below code.
app\code\vendor\extension\etc\event.xml

<pre class="lang:default decode:true">
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="restrict_sales_model_cart_add_before" instance="Vendor\Extension\Observer\CartAddRestric" />
</event>
</config>
</pre>

After that, we need to create one more “CartAddRestrict.php” inside our extension folder using below code. app\code\vendor\extension\Observer\CartAddRestrict.php

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Checkout\Model\Cart;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\Http\Context as customerSession;

class CartAddRestric implements ObserverInterface
{
    protected $cart;
    protected $messageManager;
    protected $redirect;
    protected $request;
    protected $product;
    protected $customerSession;
    public function __construct(
        RedirectInterface $redirect,
        Cart $cart,
        ManagerInterface $messageManager,
        RequestInterface $request,
        Product $product,
       customerSession $session
 )
    
        $this->redirect = $redirect;
        $this->cart = $cart;
        $this->messageManager = $messageManager;
        $this->request = $request;
        $this->product = $product;
        $this->customerSession = $session;
  
    public function execute(\Magento\Framework\Event\Observer $observer)
    
$postValues = $this->request->getPostValue();
         $cartItemsCount = $this->cart->getQuote()->getItemsCount();
      
      If($cartItemsCount >= 2)
  {
                $observer->getRequest()->setParam('product', false);
                $this->messageManager->addErrorMessage(__('You can not add product.'));
  }
    
}
</pre>

That’s it! Now whenever your customer tries to add the product in their cart from the frontend, the extension will throw an error. You can also customize this code according to your need for customization.

If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.

And, Let us know if you are facing an issue while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 11 Average: 4.8]
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

  • Hey,
    content for events.xml is missing I guess
    Could you please check once

    Thanks

Recent Posts

How to Add a Custom Field to the Cart Price Rules Form in Magento 2?

Hello Magento Friends, In this blog, we will learn How to Add a Custom Field…

4 hours ago

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

1 week ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago