How can I get order details in Magento 2?

Warning: code samples below are provided as examples only and require further customization according to your business needs.

When you are trying to get Magento 2 order collection programmatically, you may meet advice to use an object manager. But actually, Magento prohibits the direct use of the ObjectManager in your code and has strict rules on how to use this service class. We highly recommend familiarizing yourself with them because you need to avoid objectManager when you are trying to get order content. Instead, use dependency injection. 


 

Helpful tip: Display order details on the order grid with the Extended Order Grid extension. Add new columns and filters in just one click, show customer, product, shipping, or billing attributes, and organize the grid most effectively with the drag-and-drop.


 

To get Magento 2 order collection by following the best coding practices, create the code like this:

private $order;
public function __construct(
    ...
    \Magento\Sales\Api\Data\OrderInterface $order,
    ...
) {
    $this->order = $order;
}
public function getOrderId()
{
    $order = $this->order->loadByIncrementId('100005363');
    return $order->getId();
}

This code will help you get order collection by order ID in Magento 2 store without using the object manager. You can use this solution in different scenarios like restrict order based on the delivery address, offer a specific discount based on the order amount, provide users with a free product when a customer buys a particular item, etc.

For more detailed information about dependency injection and how to use it, read the official Magento documentation

See related articles:

How to add a custom column to the order grid in Magento 2

How to change the default order increment ID in Magento 2

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.