I'm adding product to cart programatically in magento 2

$this->cart->addProduct($product, ['product' => $product->getId(), 'qty' => '1']);

I want to get quote item_id using event checkout_cart_product_add_after But always return null.

My events.xml file here.

<?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="checkout_cart_product_add_after">
        <observer name="addCustomerOption" instance="Ciklum\CustomerAuth\Observer\CheckoutCartProductAddAfterObserver" />

And Observer Class.

public function execute(EventObserver $observer)
    /* @var \Magento\Quote\Model\Quote\Item $item */
    $item = $observer->getQuoteItem();

    $product = $observer->getProduct();

    echo $item->getId();exit; // always return null


Note I'm adding product programatically. Not from Controller.


2 Answers 2


You can get by below code

$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
echo $item->getId();exit;
  • did u check this one. I checked this one earlier its not working. Commented Jul 17, 2018 at 14:24
  • Yes above code is working Commented Jul 17, 2018 at 14:50
  • i already check its not working Commented Jul 17, 2018 at 15:40
  • I guess this keep happening. Looks like the QuoteItem is not properly loaded/passed and there is not ID, price, base_price etc. After adding the product again, the data is available. Magento 2.3.2. Take a look to this: github.com/magento/magento2/issues/18685 Commented Sep 30, 2019 at 13:56

You will not receive the item id from the event checkout_cart_product_add_after because the quote item is not created in the database until the same event is fully executed. So at that time there is no item id created. You can use other event checkout_cart_add_product_complete for the same.

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.