How to check if the customer is logged in or not in Magento 2?

Jun 12th, 2018 2 min to read

There are some functionalities that we want only the logged-in customers to have access to.  In order to achieve this, there must be some way to check if a customer is logged in or not.

There are two ways by which you can check if a customer is logged in or not:

1) By using Object Manager

It is always a bad practice to use ObjectManager directly.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
	$customerSession = $objectManager->get('Magento\Customer\Model\Session');
	if($customerSession->isLoggedIn()) {
	   // customer login action
	}

2) By Injecting Class (Dependency Injection)

As said earlier, it is one of the worst practices to use the ObjectManager directly. Therefore an alternate way to check if a user is logged in or not is by using the following code in any class except the template files:

You first 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 you need to use Magento\Customer\Model\Session::isLoggedIn() to check if the customer is logged in or not.

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


we forecast

Post a Comment

We don’t write crap content which is uninteresting, found everywhere and does not make any sense. Following our DNA, we write and speak about next generation technology, platforms and possibilities of digital commerce.

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.