How to redirect to previous page in Magento 2

In Magento 2, You can redirect to the previous page. This allows customers to redirect back to the page from where the customer came.

In Your Controller write the following code:

<?php
namespace Company\Module\Controller\Index;
use Magento\Framework\Controller\ResultFactory; 

class Actionname name extends \Magento\Framework\App\Action\Action
{      
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        //your code work around here

        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}

 

Leave a Reply