Magento – How to show all cart items in phtml file Magento 2

cartcheckoutmagento2phtml

What is the best way to show all the items/products that are in checkout/cart in a PHTML page?

I have added a custom phtml page that shows some products, and also have a phtml page that want to show all the products that the visitor/user have added to cart.

Thank you

Best Answer

You can get the product via quoteItem in Cart. Use this code below:

protected $cart;

public function __construct(
    \Magento\Checkout\Model\Cart $cart,
) {
    $this->cart = $cart;
}

Use this code to get the product list:

$quote = $this->cart->getQuote();
$allItems = $quote->getAllItems();

foreach($allItems as $item) {
    $product = $item->getProduct();                
}

Maybe you can use productRepository to load product by id:

\Magento\Catalog\Model\ProductRepository $productRepository

$product = $productRepository->getById($item->getProduct()->getId());

Hope it help!

Related Topic