Magento 2 – get quote by id
In this short tutorial I show you how to get quote by id in Magento 2. Sometimes this is needed to get all information related to a quote such as shipping or billing address, item data or customer related information. Based on a quote id, you can get a quote object.
Magento 2 – get quote by id
Magento 2 offers you different options to get objects by its id. The recommended one is by factory.
Factory method
The following code example demonstrate how to get a quote by its id in a PHP model. First you need to inject quote factory the following way:
1 2 3 4 5 6 7 8 9 | protected $quoteFactory; public function __construct( \Magento\Quote\Model\QuoteFactory $quoteFactory, .... ) { $this->quoteFactory = $quoteFactory; .... } |
With this factory object you can create a quote object by its id with the following line of code:
1 | $quote = $this->quoteFactory->create()->load($quoteId); |
Another option is by its repository:
Repository method
For this we need to inject a repository object instead of its factory class. This works the following way:
1 2 3 4 5 6 7 8 9 | protected $quoteRepository; public function __construct( \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, .... ) { $this->quoteRepository = $quoteRepository; .... } |
Again, we can get a quote object by its id. This time, we use the following line of code:
1 | $this->quoteRepository->get($quoteId); |
Conclusion
You can choose your preferred method to get a quote object by its id from Magento 2. If you are working on a Magento 2 module that has something to do with checkout, it is highly possible, that you need the above code. You can get a quote object in every PHP class you inject the correct class (factory or repository). So it does not depend ob type of class. You can use this in every block, helper, model or controller. If you need to pass this object to *.phtml (frontend file), you simply need to add a getter function to the correct block class. With this, you can get a quote by calling this method.
Why do you need to get a quote by its id?