How to Get Order Data by Order Increment ID Programmatically in Magento 2?

How to Get Order Data by Order Increment ID Programmatically in Magento 2?

In today’s tutorial, we will help you with a detailed guide to help you get the Order data by order increment ID in Magento 2.

It can be done using Magento\Sales\Api\OrderRepositoryInterface interface, all you need to do is use getList() function to fetch order data by order increment id.

Use the below code snippet to fetch order data by order increment id in Magento 2:

<?php
namespace Path\To\Class;
use Exception;
use Psr\Log\LoggerInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class OrderData
{
 /**
 * @var SearchCriteriaBuilder
 */
 protected $searchCriteriaBuilder;
/**
 * @var OrderRepositoryInterface
 */
 private $orderRepository;
/**
 * @var LoggerInterface
 */
 private $logger;
public function __construct(
 SearchCriteriaBuilder $searchCriteriaBuilder,
 OrderRepositoryInterface $orderRepository,
 LoggerInterface $logger
 ) {
 $this->searchCriteriaBuilder = $searchCriteriaBuilder;
 $this->orderRepository = $orderRepository;
 $this->logger = $logger;
 }
/**
 * Get Order data by Order Increment Id
 *
 * @param $incrementId
 * @return \Magento\Sales\Api\Data\OrderInterface[]|null
 */
 public function getOrderIdByIncrementId($incrementId)
 {
 $searchCriteria = $this->searchCriteriaBuilder
 ->addFilter('increment_id', $incrementId)->create();
 $orderData = null;
 try {
 $order = $this->orderRepository->getList($searchCriteria);
 if ($order->getTotalCount()) {
 $orderData = $order->getItems();
 }
 } catch (Exception $exception) {
 $this->logger->critical($exception->getMessage());
 }
 return $orderData;
 }
}

Call the function with order Increment id

$orderIncrementId = 000000001; // order increment_id
$order = $this->getOrderIdByIncrementId($orderIncrementId);
foreach ($order as $orderData) {
 $orderId = (int)$orderData->getId();
 var_dump($orderData);
}

That’s it.

You received the Order object for the var_dump in the above output.

We hope that we made everything clear about getting order data by order increment ID in Magento 2. If we missed out anything, feel free to reach us out.

Tags