3

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

  • By default, Magento minicart shows product name and quantity. – Anshu Mishra Sep 21 '18 at 5:28
  • I need to get that details in .phtml file – trilok kumar Sep 21 '18 at 5:30
  • What is your requirement? Minicart is created using ui components. – Anshu Mishra Sep 21 '18 at 5:40
  • I need to get product details in phtml file when they added to minicart.... – trilok kumar Sep 21 '18 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 Sep 21 '18 at 6:08
2

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.

| improve this answer | |
  • I have .phtml file but above code its not working Rohan Hapani – trilok kumar Sep 21 '18 at 6:41
  • Can you please post your error or log? – Rohan Hapani Sep 21 '18 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? – Rohan Hapani Sep 21 '18 at 6:44
  • Yeah i need data directly in phtml file Rohan Hapani – trilok kumar Sep 21 '18 at 6:46
  • See my updated answer. – Rohan Hapani Sep 21 '18 at 6:47

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.