Magento 2: How to redirect customer to login page

If you want to do it directly from .phtml file use following code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('\Magento\Customer\Model\Session');
$urlInterface = $objectManager->get('\Magento\Framework\UrlInterface');

if(!$customerSession->isLoggedIn()) {
    $customerSession->setAfterAuthUrl($urlInterface->getCurrentUrl());
    $customerSession->authenticate();
}

Then after login you will be automatically redirected to current view.

But using Object Manager isn't good practice. You should use dependency injection whenever possible.


@Krupali, if you're adamant about your code being implemented in a template, then @Bartlomiej Szubert's example is the better choice. Generally, it's best practice to hide away those implementation details from your template and abstract the logic away to something else (block or helper).

Here's an example of a helper implementation:

<?php

namespace Ryan\CustomerRedirect\Helper;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\UrlInterface;

class Customer extends AbstractHelper
{
    /**
     * @var Session
     */
    private $customerSession;
    /**
     * @var UrlInterface
     */
    private $urlInterface;

    public function __construct(
        Context $context,
        Session $customerSession,
    )
    {
        parent::__construct($context);
        $this->customerSession = $customerSession;
        $this->urlInterface = $context->getUrlBuilder();
    }

    public function redirectIfNotLoggedIn()
    {
        if (!$this->customerSession->isLoggedIn()) {
            $this->customerSession->setAfterAuthUrl($this->urlInterface->getCurrentUrl());
            $this->customerSession->authenticate();
        }
    }
}

Then in your template you can use something like this:

$this->helper('Ryan\CustomerRedirect\Helper\Customer')->redirectIfNotLoggedIn()

*namespace shown is an example

This way your code can be reused elsewhere...and if you decide to change the implementation logic of how you're checking if someone is logged in, you don't have to change your template(s).