Magento 2 – Programmatically Cancel Order Using Order ID

magento-2.0magento2order-statusorders

My requirement is programatically change the order status to Canceled by using order id.

How to achieve this?

Best Answer

Even though using the OrderFactory would work, save and load methods are deprecated soon, you should use service contracts instead.

So you can use Magento/Sales/Api/OrderManagementInterface:

First inject an instance in your class constructor:

protected $orderManagement;

public function __construct(
    ...
    \Magento\Sales\Api\OrderManagementInterface $orderManagement,
    ....
) {
    ....
    $this->orderManagement = $orderManagement;
    ....
}

Then use the following:

$this->orderManagement->cancel($orderId);
Related Topic