Magento 2 redirect user from observer to custom controller

Today we talk about how in Magento 2 redirect user observer custom controller. This tutorial includes example of redirect user from observer. Using this example you can redirect from block, helper and model . You need to inject \Magento\Framework\App\Response\Http class to make the redirection from anywhere.So let’s start with our example.

<?php
namespace QaisarSatti\HellowWorld\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {

    protected $_redirect;
    protected $_url;
    public function __construct(


        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\App\Response\Http $redirect,

    ) {

        $this->_url = $url;
        $this->_redirect = $redirect;

    }
    public function execute(Observer $observer) {
             $event = $observer->getEvent();
             $CustomRedirectionUrl =          $this->_url->getUrl('test/test/test');
             $this->_redirect->setRedirect($CustomRedirectionUrl);

    }
}

Note: You can use this example with any observer event.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply