0

After a customer is logged in, when I check if the customer is logged in or not, it returns true only on the customer account page and returns false on every other page like home page, product page, etc. This is the code which I am using to check

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

  $customerSession = $objectManager->get('Magento\Customer\Model\Session');

    <?php if($customerSession->isLoggedIn()) {
        echo "YEs logged in";


     }?> 
  • 1
    try this answer – Piyush Aug 9 '19 at 6:21
  • @Piyush Thank you. this worked for me – Nafisa Aug 9 '19 at 6:44
0

Note: You should not use an objectmanager directly into the code.

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 in your function in the same class, you can call the following:

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

Also you can create method which return true or false whether a customer is logged in or not:

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

You can call this method in your block's template file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.