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.


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. Jul 17 '18 at 14:24
  • Yes above code is working Jul 17 '18 at 14:50
  • i already check its not working Jul 17 '18 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 Sep 30 '19 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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