Categories
Magento

How to check if a customer is logged in?

Let’s discuss, how to check if the customer is logged in at any class (controller, model, block, etc) or at the template.

First of all, please do not use the ObjectManager directly.

The method isLoggedIn() contained in the /Magento/Customer/Model/Session class. So you need to use this class at your constructor:

protected $_customerSession;    // do not use `$_session` name for this because it is already used in \Magento\Customer\Model\Session

public function __construct(
    ...
    \Magento\Customer\Model\Session $session,
    ...
) {
    ...
    $this->_customerSession = $session;
    ...
}

Then you can use the method isLoggedIn() at your code something like this:

if ($this->_customerSession->isLoggedIn()) {
    // is logged in 
} else {
    // is NOT logged in
}

If you need to determine the customer is logged in at the template, you should deal with blocks. If you have your own block, then just use the method above: use class at the constructor and its method. Otherwise, first, you should override the block to add the method. Use preference for it:

<preference for="Some\Block\You\Need\Override"
            type="Vendor\Module\Block\Your\Custom\Block" />

Then at the block declare _customerSession property at the constructor and create this method:

public function isCustomerLoggedIn()
{
    return $this->_customerSession->isLoggedIn();
}

Now, in your template you can call:

if ($block->isCustomerLoggedIn()) {
    // is logged in
} else {
    // is NOT logged in
}

Leave a Reply

Your email address will not be published. Required fields are marked *