
Magento 2.x – Validate if a customer is logged in or not
To check if customer is loged in or not you can call Magento\Customer\Model\Session::isLoggedIn() method.
If you want to do that properly in *.phtml files you should use helper inside the template, you will see a ton of examples using the ObjectManager, but you should always bear in mind that it’s not a good coding practice.
So, let’s perform the following steps:
- Create YourCompany\ModuleName\Helper\Data
123456789101112131415161718<?phpnamespace YourCompany\ModuleName\Helper;class Data extends \Magento\Framework\App\Helper\AbstractHelper{public function __construct(\Magento\Framework\App\Helper\Context $context,\Magento\Customer\Model\Session $customerSession) {$this->customerSession = $customerSession;parent::__construct($context);}public function isLoggedIn(){return $this->customerSession->isLoggedIn();}} - Use the previous Helper, in your phtml as follows:
123456<?php $helper = $this->helper('YourCompany\ModuleName\Helper\Data'); ?><?php if($helper->isLoggedIn()) : ?>logged in<?php else : ?>not logged in<?php endif; ?>
Before trying, remember to re-compile, and clean cache.