2

In Magento 1 it's done like this

$quote = Mage::getSingleton('checkout/cart')->getQuote();

$cartItems = $quote->getItemByProduct($product);

Is it possible in Magento 2?

0
 public function __construct(\Magento\Checkout\Model\Session $checkoutSession) 
 {
    $this->checkoutSession = $checkoutSession;
}

    $quote = $this->checkoutSession->getQuote();
    $cartItems = $quote->getItemByProduct($product);
3
0

Same in Magento 2.

You can inject Quote Session (\Magento\Checkout\Model\Session) and use getItemByProduct function.

Example: Inject Quote Session

/**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @param \Magento\Checkout\Model\Session $checkoutSession
     */
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession
    ) {   
        $this->_checkoutSession = $checkoutSession;
    }

And use getItemByProduct function

$this->_checkoutSession->getQuote()->getItemByProduct($product);
0

Use Below code for it

    <?php
namespace Vendor\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{
  protected $_productloader; 
  protected $_checkoutSession; 
  public function __construct(
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Checkout\Model\Session $checkoutSession

    ) {

        $this->_productloader = $_productloader;
        $this->_checkoutSession = $checkoutSession;
    }
    public function getItemById()
    {
        $product=$this->_productloader->create()->load($id);
        $quote = $this->_checkoutSession->getQuote();
        $cartItems = $quote->getItemByProduct($product);
    }

}

Or you can use Below code

$om =   \Magento\Framework\App\ObjectManager::getInstance();
$quote = $om->create('Magento\Checkout\Model\Cart')->getQuote();
$product = $om->get('Magento\Catalog\Model\Product')->load($product_id);
$item = $quote->getItemByProduct($product);
0

Use this below code :

protected $_productFactory;
protected $checkoutSession;

public function __construct(
    ..........
    \Magento\Catalog\Model\ProductFactory $_productFactory,
    \Magento\Checkout\Model\Session $checkoutSession
    ..........
) 
{
    ..........
    $this->checkoutSession = $checkoutSession;
    $this->_productFactory = $_productFactory;
    ..........
}

public function execute()
{
    $quote = $this->checkoutSession->getQuote();
    $product = $this->_productFactory->create()->load($product_id);
    $_item = $quote->getItemByProduct($product);
}

Note : Do not use ObjectManager Directly.

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.