i created an observer before add to cart like this:

<?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="test_custom_controller_action_predispatch_checkout_cart_add" instance="Test\Custom\Observer\BeforeAddCart" />

in this observer i want to check if the cart is empty and do some function, before add product to the cart

  • Accept the answer If you find it helpful @Hunter
    – Keyur Shah
    Aug 23, 2017 at 11:13

3 Answers 3


You can also use the cart helper

 protected $cartHelper;

 public function __construct(     
        \Magento\Checkout\Helper\Cart $cartHelper
    ) {
        $this->cartHelper = $cartHelper;

and then you can do the check

   if ($this->cartHelper->getItemsCount() === 0) {
          //add your functionality

You can get item count using below way,

namespace Test\Custom\Observer;

use Magento\Framework\Event\ObserverInterface;

class BeforeAddCart implements ObserverInterface
    public function execute(\Magento\Framework\Event\Observer $observer)
        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $observer->getEvent()->getQuoteItem();
        echo count($item);exit;
  • You are too fast :) @Rakesh
    – Keyur Shah
    Aug 21, 2017 at 7:24
protected $_cart;      

public function __construct(     
    \Magento\Checkout\Model\Cart $_cart
) {
    $this->_cart = $_cart;

Now you can use this like,

    // do your stuff here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.