Check if Customer is Logged in or not in Magento 2

As we all know, there are so many condition where we need to check whether customer is currently logged in or not for specific functionality. In this blog post you will have idea about how to check if customer is logged in or not in Magento 2.

It is always best practice to do not use ObjectManager directly. You can use following code to check user is logged in or not in any class except template files.

You need to use this Magento\Customer\Model\Session::isLoggedIn() method in following way.  First you need to inject the following class in your constructor: /Magento/Customer/Model/Session

protected $_session;

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

Then in you class you can use following snippet of code anywhere.

if ($this->_session->isLoggedIn()) {
    // Customer is logged in 
} else {
    // Customer is not logged in
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s