Skip to content

Magento 2: change order status programmatically

I need to set in “canceled” all orders stucks in “pending” status. The code that I used return this exception error:

[2022-12-03 08:00:53] main.CRITICAL: Please provide payment for the order.

Here the code:

use MagentoSalesModelOrder;

protected $order;

public function __construct(Order $order)
{
    $this->order = $order;
}

public function orderStatusChange()
{
    $orderId = 9999;
    $order = $this->order->load($orderId);
    $order->setStatus("canceled");
    $order->save();
}