Magento 2.1.1 Load Order by Increment ID Using OrderRepository

magento-2.1magento2moduleorders

What would be the latest best practice to load Order using increment ID (instead of Order ID) using OrderRepository

Best Answer

Magento 2 uses Service Contracts for retrieving and saving objects. In Magento this layer is formed by Repositories, which are managers with get() and save() methods. This keeps user code away from Model calls. Don't call model methods (like load() or save() or loadByIncrementId()) directly, they are being deprecated as custom code should use the Service Contracts. Also, don't use the API from within Magento like Khoa is suggesting, it does not make sense. The API is for connecting Magento with other systems.

Inject OrderRepository and SearchCriteriaBuilder in your constructor:

private $orderRepository;
private $searchCriteriaBuilder;

public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Sales\Model\OrderRepository $orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
){
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
parent::__construct($context);
}

And in your function:

$searchCriteria = $this->searchCriteriaBuilder
    ->addFilter('increment_id', '000000001', 'eq')->create();
$orderList = $this->orderRepository->getList($searchCriteria)->getItems();

// $orderList is now an array of Orders with this incrementId, which is just one order obviously

/** @var \Magento\Sales\Model\Order $order */
$order = reset($orderList);
// Your logic here
$order = $this->orderRepository->save($order);

Official Magento PHP Developer guide on magento.com

Code by Mulderea on github