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.