Magento 2 – Get All Items in Cart Using Quote ID

cartmagento2quotequoteitem

Is there a way to load all items in cart, only using quote entity_id from quote table in magento 2 database?

Best Answer

I assume you want to get that in a class.
If not, you should.

Let's say the class name is Vendor\Module\Model\QuoteItems. It should look like this:

<?php 
namespace  Vendor\Module\Model;

class QuoteItems
{
    protected $quoteRepository;
    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    )
    {
        $this->quoteRepository = $quoteRepository;
    }
    public function getQuoteItems($quoteId)
    {
         try {
             $quote = $this->quoteRepository->get($quoteId);
             $items = $quote->getAllItems();
             return $items;
         } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
             return [];
         }
    }
}

then you can use your class to retrieve the items with the method getQuoteItems.
Or you can use the code inside the method directly, just by injecting an instance of the quote repository in your class.

Related Topic