How to check if customer is logged in or not?

How to check if customer is logged in or not? 

1) Using Object Manager.

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

2) From Controller.

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // Yes customer is logged in
}

3) From Block or Model Or Helper.

protected $customerSession;

public function __construct(
    \Magento\Customer\Model\SessionFactory $customerSession
) {
    $this->customerSession = $customerSession;
}

public function isLoggedIn() // use this function in phtml file
{
    return $this->customerSession->create()->isLoggedIn();
}

If like efforts, Please share, comment and subscribe for future posts and inspire more.

Comments

Popular posts from this blog

Hosting and Goodies

Magento 2 Import Scripts

How to add product attribute value in minicart magento 2