How to Get Order Data from “sales_order_place_after” Event in Magento 2?

How to Get Order Data from “sales_order_place_after” Event in Magento 2?

An order is placed after completing the checkout process. After the order is placed, its data may be needed for several purposes. Admin may want to retrieve the order status or the complete order data to send it to the customer for the confirmation of their order. Shipping carriers also need the complete order data for their delivery. Similarly, admin may want to push order data to third party web service or to calculate tax based on order attributes.

Order data is retrieved using Magento Events and Observers which are central to extending Magento functionality. Magento also allows creating custom events in addition to its own events. Events are dispatched when certain actions are triggered and pass data to the Observer.

Steps to Get Order Data from “sales_order_place_after” Event

Step 1: Create event.xml file at app/code/Vendor/Extension/etc/

 
<?xml version="1.0"?>
<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<eventname="sales_order_place_after">
<observername="place_order_after" instance="Vendor\Extension\Observer\OrderdataObserver" />
</event>
</config>

Step 2: Create the Observer file OrderdataObserver at app/code/Vendor/Extension/Observer/

 
<?php 
namespace Vendor\Extension\Observer; 
use Magento\Framework\Event\ObserverInterface; 
use Psr\Log\LoggerInterface; 
class OrdedataObserver implements ObserverInterface 
{ 
protected $logger; 
public function __construct(LoggerInterface$logger) 
{ 
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
 try 
{
    $order = $observer->getEvent()->getOrder();
}
catch (\Exception $e) 
{
 $this->logger->info($e->getMessage());
}
  }
}

This is as simple as it is. You can modify the code to get the order id or any other particular order information. Checkout this tutorial to get order information by order ID.

If you are facing any issue with getting Order Data from “sales_order_place_after” Event in Magento 2, don’t hesitate to contact us.

Related Articles: