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


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!

  • Thank you for your comment, but where should I put the code: protected $cart; public function __construct( \Magento\Checkout\Model\Cart $cart, ) { $this->cart = $cart; } At which file? p.s. dont forget its magento 2
    – Algert Zh
    Dec 29 '17 at 11:27
  • You can add that code inside the __construct function of your Block file. After that, create a function that return the list of Item. And in the phtml file, you can call the foreach to get the list item and get the product.
    – Nero Phung
    Dec 29 '17 at 11:55
  • I have added that code to /app/code/company/theme/Block/Template.php and im getting this error: Error filtering template: Notice: Undefined property: Magento\Framework\View\Element\Template::$cart in /home/user/public_html/20189/vendor/magento/framework/View/TemplateEngine/Php.php on line 110
    – Algert Zh
    Jan 3 '18 at 12:05
  • Seem like you have defined the $cart is Magento\Framework\View\Element\Template. Change it to \Magento\Checkout\Model\Cart
    – Nero Phung
    Jan 3 '18 at 15:41
  • Hello, I tried to put the code at: /vendor/magento/module-checkout/Model/Cart.php and I receive this error: Error filtering template: Class Magento\Checkout\Model\Cart does not exist Can you please help me at which file should I put the code ? Thank you
    – Algert Zh
    Jan 4 '18 at 11:52

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.