Get Order Details by Order Id in Magento 2

Get Order Details by Order Id in Magento 2

To get order details by order id in Magento 2 we use \Magento\Sales\Api\OrderRepositoryInterface Class in which we pass the order id after adding its dependency in our custom class.

Today in this topic we will check how to get order details by order id in Magento 2.

First Step:

Add dependency in our custom class or the class where you need to get the order details.

<?php 

use Psr\Log\LoggerInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

public function __construct(
    LoggerInterface $logger,
    OrderRepositoryInterface $orderRepository,
){
    $this->logger = $logger;
    $this->orderRepository = $orderRepository;
}

Second Step:

Now call the dependency function in your class to load the Order by Id and get the required details from the Order Object that we get.

public function getOrderDetails
{
    $orderId = '10';
    $order = $this->orderRepository->get($orderId);

    $orderItems = $order->getAllVisibleItems();
    foreach ($orderItems as $item)
    {
        $item_qty_ordered = (int)$item->getQtyOrdered();
        $price = $item->getBasePrice();
    }

    $customer_email = $order->getCustomerEmail();

    $payment = $order->getPayment();
    $payment_method = $payment->getMethod();

    $shipping_charges = $order->getBaseShippingAmount();
    $sub_total = $order->getBaseSubtotal();
    $grand_total = $order->getBaseGrandTotal();
    $discount_amount_string = $order->getBaseDiscountAmount();

    $shipping_address = $order->getShippingAddress();
    $billing_address = $order->getBillingAddress();

    //shipping address
    $ship_customer_name = $shipping_address->getFirstname()." ".$shipping_address->getLastname();
    $ship_address = $shipping_address->getStreet()[0];

    $ship_phone = $shipping_address->getTelephone();
    $ship_area_code = $shipping_address->getPostcode();
    $ship_city = $shipping_address->getCity();
    $ship_state = $shipping_address->getRegion();
    $ship_email = $shipping_address->getEmail();

    //billing address
    $bill_customer_name = $billing_address->getFirstname()." ".$billing_address->getLastname();
    $bill_address = $billing_address->getStreet()[0];

    $bill_phone = $billing_address->getTelephone();
    $bill_area_code = $billing_address->getPostcode();
    $bill_city = $billing_address->getCity();
    $bill_state = $billing_address->getRegion();
    $bill_email = $billing_address->getEmail();
}

So, using the above OrderRepositoryInterface Class we have gotten the Order details which we can use as per our needs.

Check the Magento 2 OrderRepositoryInterface file in Github for more information.

I hope this helps! If you have any further questions, please don’t hesitate to reach out.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments