Magento 2 – How to Get Product Name and Qty in Mini Cart

magento2mini-cart

Magento 2 how to get product name and its qty in mini cart when we add to mini cart

Best Answer

Try to use this code :

Factory Method :

protected $_cart;
public function __construct(
    ..................................
    \Magento\Checkout\Model\Cart $cart,
    ..................................
) {
    ..................................
    $this->_cart = $cart;
    ..................................
}


public function yourfunction()
{
    $cartProductList = $this->_cart->getQuote()->getAllItems();
    foreach($cartProductList as $item) {
        echo 'ID: '.$item->getProductId().'<br />';
        echo 'Name: '.$item->getName().'<br />';
        echo 'Sku: '.$item->getSku().'<br />';
        echo 'Quantity: '.$item->getQty().'<br />';
        echo 'Price: '.$item->getPrice().'<br />';
        echo "<br />";            
      }
}

Object Manager Method :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
$cartProductList = $cart->getQuote()->getAllItems();

foreach($cartProductList as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}

It will helpful for you.

Related Topic