3

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

7
  • By default, Magento minicart shows product name and quantity. Commented Sep 21, 2018 at 5:28
  • I need to get that details in .phtml file Commented Sep 21, 2018 at 5:30
  • What is your requirement? Minicart is created using ui components. Commented Sep 21, 2018 at 5:40
  • I need to get product details in phtml file when they added to minicart.... Commented Sep 21, 2018 at 5:48
  • So where do you need that data? you can create default.html file under Magento_Checkout->web->template->minicart->item, and edit the default layout of mini cart, like add sku of products and ... . But where do you want to show that data?
    – Korbin
    Commented Sep 21, 2018 at 6:08

1 Answer 1

3

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.

9
  • I have .phtml file but above code its not working Rohan Hapani Commented Sep 21, 2018 at 6:41
  • Can you please post your error or log? Commented Sep 21, 2018 at 6:42
  • If you want to get data direct in phtml file then you need to get data by object manager. You want to get direct in phtml? Commented Sep 21, 2018 at 6:44
  • Yeah i need data directly in phtml file Rohan Hapani Commented Sep 21, 2018 at 6:46
  • See my updated answer. Commented Sep 21, 2018 at 6:47

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.