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

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