I tried the below code but when the cache is disabled. it works, but when I enable cache it does not work.
Overview of retrieving the data of shopping cart items, subtotal, grand total, billing & shipping address in Magento 2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
echo $totalItems = $cart->getQuote()->getItemsCount();
echo $totalQuantity = $cart->getQuote()->getItemsQty();

I know that we do not use an object manager. I will change the code.

  • I am facing the same issue. – Biren Patel Dec 24 '19 at 10:00

You can't with cache enabled, all files aren't re-interpreted.

You should get it with customer data. You can try to add the following code in your phtml file.

<script type="text/javascript">
    ], function (customerData) {
        'use strict';

        customerData.get('cart').subscribe(function (cartInfo) {
        }, this);
| improve this answer | |

I think this code will help you!!

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

        // get quote items collection
        $itemsCollection = $cart->getQuote()->getItemsCollection();

        // get array of all items what can be display directly
        $itemsVisible = $cart->getQuote()->getAllVisibleItems();

        // get quote items array
        $items = $cart->getQuote()->getAllItems();

        foreach($items as $item) {
/*for example below attribute access it*/
            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 />";            

I hope this will help you!!

| improve this answer | |
  • Thanks! For the reply. I applied the same logic if you can check the above code. – Kushal Dec 24 '19 at 10:19

Try this

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

  foreach ($quoteItems as $item ){
        echo $item->getQty();
| improve this answer | |

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.