Magento – Get quote item id after product added to cart in observer

event-observermagento2quoteitem

I am working on a custom module where a single product of a certain sku (say fixed-product) will be added to cart multiple times, but with different custom options programmatically. I also need to store it's item_id in another custom table for later use.

I managed to display the different products as separate entities on the cart (instead of just adding the quantity) by rewriting the Codilar\ProfServices\Model\Rewrite\CartItem::representProduct() method to return false if the conditions are met.

But I cannot obtain the item_id of the item once it's added to cart. I tried the following events

checkout_cart_product_add_after and sales_quote_item_set_product

but in the observer when I do $this->getEvent()->getQuoteItem()->getItemId() it always returns NULL

How do I get the item_id of an item added to cart in the observer?

Best Answer

For checkout_cart_add_product_complete event

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Session as CheckoutSession;

class CheckoutCartAddProductCompleteObserver implements ObserverInterface
{
    private $_checkoutSession;

    public function __construct(
        CheckoutSession $checkoutSession
    )
    {
        $this->_checkoutSession = $checkoutSession;
    }

    public function execute(EventObserver $observer)
    {
        /** @var \Magento\Catalog\Model\Product $product */
        $product = $observer->getEvent()->getDataByKey('product');

        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $this->_checkoutSession->getQuote()->getItemByProduct($product);

        $itemId = $item->getId();
    }
}