2

I am trying to get the last order so that I can load the order by increment id but

`$this->_checkoutSession->getLastRealOrder()->getIncrementId()`;

is returning null.

4
  • Can you give some more context where you are using this and why you need it? There is a lot of ways to do this Nov 6, 2017 at 8:30
  • This is solved, I deleted and reinstalled magento 2 with sample data. Nov 8, 2017 at 5:09
  • after placeOrder the checkoutSession didn't in my case return the orderId, only the quote was available, is this an issue ?
    – medmek
    Jul 17, 2018 at 14:31
  • @medmek I am facing the same issues, after placeOrder, I am not able to fetch the getLastRealOrderId form checkout session, it works sometimes and sometimes it does not
    – Dhimant
    Jul 24, 2021 at 14:18

1 Answer 1

0

Use this code in your block class or helper:

protected $_checkoutSession;
protected $_orderFactory;
protected $_scopeConfig;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Sales\Model\OrderFactory $orderFactory,
    \Magento\Framework\View\Element\Context $context
) {
    $this->_checkoutSession = $checkoutSession;
    $this->_orderFactory = $orderFactory;
    $this->_scopeConfig = $context->getScopeConfig();
}


// Use this method to get ID    
public function getRealOrderId()
{
    $lastorderId = $this->_checkoutSession->getLastOrderId();
    return $lastorderId;
}

public function getOrder()
{
    if ($this->_checkoutSession->getLastRealOrderId()) {
         $order = $this->_orderFactory->create()->loadByIncrementId($this->_checkoutSession->getLastRealOrderId());
    return $order;
    }
    return false;
}

public function getShippingInfo()
{
    $order = $this->getOrder();
    if($order) {
        $address = $order->getShippingAddress();    

        return $address;
    }
    return false;

}

Using this function, you can get the latest order Id. Hope this will help you too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.