Magento – magento 2 unable to redirect to external url from observer

event-observerlogmagento2module

I made modules that work fine but unable to redirect to another url when event fired

what code does when adding to cart is pressed I want to redirect to other URL say google.com

my module works as a log file is generated.

I also get error when i inspected console:

Fatal error: Call to undefined method Devshree\Affliliate\Observer\GetQuote::_redirect() in /var/www/html/magento/app/code/Devshree/Affliliate/Observer/GetQuote.php on line 15

below is my code :

Devshree\Affliliate\etc\frontend\events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_save_before">
        <observer name="devshree_affliliate_event_obs" instance="Devshree\Affliliate\Observer\GetQuote" />
    </event>
</config>

Devshree\Affliliate\Observer\GetQuote.php

namespace Devshree\Affliliate\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

    class GetQuote implements ObserverInterface {
        public function execute(Observer $observer) {
            $myfile = fopen("/var/www/html/magento/var/logdebug.log", "a+") or die("Unable to open file!");
            $abc = "heello";
            fwrite($myfile, print_r($abc,true));
            fclose($myfile);
            return $this->_redirect('*/auth/login');
        }
    }

Best Answer

You can redirect to external URL from observer like below :

namespace Devshree\Affliliate\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Response\RedirectInterface;

class GetQuote implements ObserverInterface {

    protected $_redirect;
    protected $_response;

    public function __construct(
        RedirectInterface $redirect,
        ResponseInterface $response 
    ){
        $this->_redirect = $redirect;
        $this->_response = $response;
    }
    public function execute(Observer $observer) {
        $myfile = fopen("/var/www/html/magento/var/logdebug.log", "a+") or die("Unable to open file!");
        $abc = "heello";
        fwrite($myfile, print_r($abc,true));
        fclose($myfile);
        $this->_redirect->redirect($this->_response, '*/auth/login');
    }
}
Related Topic