Magento – Magento 2 : Redirect on cart page after login

customermagento2redirect

I want to redirect the customer to cart page after login from anywhere ex.login from checkout page or customer account login.

Anyone know how to do this?

Please help me.

Best Answer

Step 1 : Create

Vendor/Module/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="customer_login">
        <observer name="customer_login_observer" instance="Vendor\Module\Observer\CustomerLogin" />
    </event>

</config>

Step 2 :

Create Vendor/Module/Observer/CustomerLogin.php

<?php

namespace Vendor\Module\Observer;

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

class CustomerLogin implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;

    public function __construct(
        \Magento\Framework\View\Layout $layout,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
    )
    {   
        $this->_layout = $layout;
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /*$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl('checkout/cart');
        return $resultRedirect;*/
        $RedirectUrl = $this->_url->getUrl('checkout/cart');
        $this->_responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();
        die();
    }
}