Magento 2: quote data is not working with cache enable

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!!


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">
    require([
        'Magento_Customer/js/customer-data'
    ], function (customerData) {
        'use strict';

        customerData.get('cart').subscribe(function (cartInfo) {
            console.log(cartInfo['summary_count']);
        }, this);
    });
</script>