3

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

1 Answer 1

0

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!

13
  • 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 Dec 29, 2017 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, 2017 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 Jan 3, 2018 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, 2018 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 Jan 4, 2018 at 11:52

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.