0

I want to see if there is anything exists in the cart if I am in a phtml page

I have tried to use session and cart but I am getting null When I tried to use session I wasn’t sure how to get the quote ID in order to get cart ID but I don’t know which is the right approach to take Could anyone help me out with this

0

Something like this should work

app/code/Xigen/Cart/Helper/Quote.php

namespace Xigen\Cart\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Quote extends AbstractHelper
{

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->cart = $cart;
        parent::__construct($context);
    }

    public function getAllVisibleItems() {
        return $this->cart->getQuote()->getAllVisibleItems();
    }

    public function getAllVisibleItemsCount() {
        return count($this->getAllVisibleItems());
    }
}

Then in template for example

$visibleItems = $this->helper('\Xigen\Cart\Helper\Quote')->getAllVisibleItemsCount();

  • How does it know to take the active cart? I mean for each customer a different cart. – vitoriodachef May 28 at 20:35
  • 1
    It's always only the cart of the current session. Unless the block is cached of course. – Dominic Xigen May 28 at 20:43
  • 1
    I was about to say the session as well. @DominicXigen thank you for this I will take a look at this and get back to you. Thanks for showing the count part – Jack Brooks May 28 at 20:46
  • @DominicXigen hi there. I have tried this it worked for maybe once like it did work but then when I refresh the page it won’t come up like it’s null but my cart has product – Jack Brooks May 29 at 19:31
  • Can you disable frontend caches and see if still the same php bin/magento cache:disable layout block_html full_page – Dominic Xigen May 29 at 20:27

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.