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.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<observer name="restrict_sales_model_cart_add_before" instance="Vendor\Extension\Observer\CartAddRestric" />
After that, we need to create one more “CartAddRestrict.php” inside our extension folder using below code. app\code\vendor\extension\Observer\CartAddRestrict.php
use Magento\Framework\App\Http\Context as customerSession;
class CartAddRestric implements ObserverInterface
public function __construct(
$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)
$this->messageManager->addErrorMessage(__('You can not add product.'));
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.