How to check whether a customer is logged in or not in Magento 2

There were many situations, while developing an extension, when we need to check that whether the customer  is logged or not. The following code will help you to check:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // code you need to perform when customer is logged in
}

As you can check the above method uses object manager and it is not a best practice to use the object manager directly. So if in controller you need to check whether the customer is logged in or not then provide the object manager dependency in constructor and then use following code:

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // code you need to perform when customer is logged in
}

Hope this will help you. If you have another solution please mention in comment box. If you need any other help in coding please comment below.

Leave a Reply

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