How to get Order details using Order id In Magento 2?

Order ID In Magento 2

In this blog, We will see how to get order details by using order id in magento 2. Order details contains the order information like Total summary, Customer Information, Billing, shipping and payment-related data in Magento 2.

Using Dependency Injection (DI), You can use inject \Magento\Sales\Api\OrderRepositoryInterface class to get order details using order id.

Below way, you can get order details using order id in Magento 2.

  • 1. Create a OrderDetails.php file in the app/code/Magespark/OrderDetails/Block folder with the following code:
    <?php
    
    namespace MageSpark\OrderDetails\Block;
    
    use Magento\Sales\Api\OrderRepositoryInterface;
    
    class OrderDetails {
    
       /**
        * @var OrderRepositoryInterface
        */
       protected $orderRepository;
    
       /**
        * OrderDetails constructor.
        * @param OrderRepositoryInterface $orderRepository
        */
       public function __construct(
           OrderRepositoryInterface $orderRepository
       ) {
           $this->orderRepository = $orderRepository;
       }
    
       /**
        * Get Order by Order ID
        * @param $id
        * @return OrderRepositoryInterface
        */
       public function getOrderDetails($id)
       {
           return $this->orderRepository->get($id);
       }
    }
  • 2. Create a template.phtml file in the app/code/Magespark/OrderDetails/view/frontend/templates folder with the following code:
    <?php
    
    /** @var  $block \MageSpark\OrderDetails\Block\OrderDetails */
    // Let's assume, We've order id is 1
    $orderId = 1;
    
    // Call function using order id
    $order = $block->getOrderDetails($orderId);
    
    // Display all details of specific order id.
    print_r($order->debug());
    
    // Display Customer Name of specific Order using orderId.
    echo $order->getCustomerName();
$block variable is referencing our block class and we are calling the method getOrderDetails which is returning the string Order Object. Happy integrating! 😊
Talk to a Hyvä expert
Loading...