Get Customer Login URL in Magento 2

0
18956
Get Customer Login URL in Magento 2
Get Customer Login URL in Magento 2

In today quick tip, I will show you how to get customer login URL in Magento 2, which is very necessary when you want to render in block template.

By default, if you’re in the template, the block instance already has a method to get URL of any route, which is getUrl(). So to get customer login URL, you can make a call like this:

$this->getUrl('customer/account/login')

Another way to get customer login URL is to use customer URL model. For that, you will need to inject into block or any class an instance of `\Magento\Customer\Model\Url` , let say you inject into a constructor:

public function __construct(\Magento\Customer\Model\Url $url) 
{
    $this->customerUrl = $url;
}

public function getCustomerLoginUrl()
{
    return $this->customerUrl->getLoginUrl();
}

Both methods work the same way, no difference. It is up to where you are in the code.

Also, if you want to get customer login URL, then after logging in, you want to redirect customers back to where they were before, try this:

$url = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
$loginUrl = $block->getUrl('customer/account/login', array('referer' => base64_encode($url)));

The referer query parameter will determine which URL to redirect customers back after logging in.

Have fun ~