How to Get Order Details by Order Id in Magento 2

In this article we'll discuss how to get order information by order id in Magento 2. You can retrieve order details by order ID using code within a custom module. The standard way to get order details by order ID in Magento 2 is by using dependency injection and repositories.

Here's an example within a custom controller class. You can retrieve order information by order ID using the OrderRepository any anywhere else as per your requirement.

saveCopyzoom_out_map
<?php declare(strict_types=1); namespace Devhooks\ModuleName\Controller\Order; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Sales\Api\OrderRepositoryInterface; class Details extends Action { /** * @var OrderRepositoryInterface */ private $orderRepository; /** * @param Context $context * @param OrderRepositoryInterface $orderRepository */ public function __construct( Context $context, OrderRepositoryInterface $orderRepository ) { parent::__construct($context); $this->orderRepository = $orderRepository; } public function execute() { $orderId = 1; // Replace with the actual order ID you want to retrieve try { $order = $this->orderRepository->get($orderId); // Now you have the order object and can access its details echo "Order ID: " . $order->getIncrementId() . "\n"; echo "Order Status: " . $order->getStatus() . "\n"; // Get items in the order $items = $order->getAllVisibleItems(); foreach ($items as $item) { echo "Product ID: " . $item->getProductId() . "\n"; echo "Product Name: " . $item->getName() . "\n"; echo "Product Price: " . $item->getPrice() . "\n"; echo "Product SKU: " . $item->getSku() . "\n"; echo "Quantity: " . $item->getQtyOrdered() . "\n"; } } catch (\Exception $e) { echo "Order not found"; } } }

In this example, a controller Details is created, and the OrderRepositoryInterface is injected into it using dependency injection. The execute() method retrieves the order by its ID using the repository's get() method. Then, it accesses the order's basic details and iterates through the order items.

Remember to replace 1 in $orderId with the actual order ID you want to retrieve details for.

This adheres to Magento's best practices by using repositories for data retrieval instead of directly interacting with models, providing a more standardized and maintainable approach.

That’s it!!

I hope this article helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this article with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off