0

I'm trying to get access to all items in the shopping cart in a block, but I can't seem to get them. If I try the code below to construct and $items = $this->_cart->getQuote()->getAllVisibleItems(); then I get an empty array. Plus this is a deprecated model. Also when I try using Magento\Checkout\Model\Session I get an empty array for $items = $this->_session->getQuote()->getAllVisibleItems();.

How are you supposed to get the items in the shopping cart in Magento 2.4?

Older methods don't seem to work

public function __construct(
    Template\Context $context,
    \Magento\Checkout\Model\Cart $cart,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->_cart = $cart;
}

1 Answer 1

1

Try below code and check.

In Magento 2.4, you can use the \Magento\Checkout\Block\Cart block to access the cart items.

You can inject the \Magento\Checkout\Block\Cart block into your custom block's constructor and use it to access the cart items.

<?php

namespace [Vendor]\[Module]\Block;

use Magento\Checkout\Block\Cart;

class YourBlock extends \Magento\Framework\View\Element\Template
{
    protected $cart;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        Cart $cart,
        array $data = []
    ) {
        $this->cart = $cart;
        parent::__construct($context, $data);
    }

    public function getCartItems()
    {
        return $this->cart->getItems();
    }
}

You can now use the getCartItems() method in your template file to access the cart items.

In addition to that, you can also use the \Magento\Checkout\Model\Session class to get the cart items,

<?php
use Magento\Checkout\Model\Session as CheckoutSession;

class YourBlock extends \Magento\Framework\View\Element\Template
{
    protected $checkoutSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        CheckoutSession $checkoutSession,
        array $data = []
    ) {
        $this->checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }

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

You can now use the getCartItems() method in your template file to access the cart items.

Let me know if any query.

THANKS.

1
  • the first solution is the only one that gets the cart items outside the checkout page. Second solution only works on the checkout page Commented Mar 14 at 14:59

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.