Magento 2 Error: getLastRealOrderId Doesn’t Work After Checkout With Enabled Page Cache

magento 2 error getLastRealOrderId not working after checkout with enabled page cache

PROBLEM:

Creating a payment gateway module in order to redirect to the gateway page after checkout. However, while page cache is enabled the method for getting the last real order id returns null (it is used to get order id from the session).

So, how to use the module without disabling page cache?

SOLUTIONS:

There are 2 simple steps to handle this Magento 2 error:

  • Step 1: Defining the constructor – pass Magento\Framework\App\Cache\TypeListInterface and Magento\Framework\App\Cache\Frontend\Pool to your file’s constructor like the following:
public function __construct(
    Context $context,
    \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
    \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) {
    parent::__construct($context);
    $this->_cacheTypeList = $cacheTypeList;
    $this->_cacheFrontendPool = $cacheFrontendPool;
}
  • Step 2: Add the following code to the method where you want clear/ flush cache:
$types = array('config','layout','block_html','collections','reflection','db_ddl','eav','config_integration','config_integration_api','full_page','translate','config_webservice');
foreach ($types as $type) {
    $this->_cacheTypeList->cleanType($type);
}
foreach ($this->_cacheFrontendPool as $cacheFrontend) {
    $cacheFrontend->getBackend()->clean();

We have shown you 2 quick steps to deal with the Magento 2 error: getLastRealOrderId doesn’t work after checkout with enabled page cache. If you have any difficulties when following our instructions, be free to leave the comment below.

See More Magento Tutorials:

[Fix It Series] Front Controller Reached 100 router Match Iterations

How To Clear Cache In Magento 2

2 thoughts on “Magento 2 Error: getLastRealOrderId Doesn’t Work After Checkout With Enabled Page Cache

  1. Michael Mussulis says:

    Hi,

    Is the cache clearing meant to go before the payment gateway redirect or in the return controller of the payment module?

    Thanks,
    Michael.

    • Mark Mac says:

      Hey Michael, feel free to email us your question, as it would be quite lengthy to answer your question here. All the best!

Leave a Reply

Your email address will not be published. Required fields are marked *