Magento 2 customer logged in or not
A common task for Magento 2 modules is to check if customer logged in or not. Magento core use this query to check if a customer is able to see and buy products or may see customer group related prices. You can also influence this or simple output text only for logged in customers (newsletter opt in for example).
Magento 2 customer logged in or not
All you need for this is an instance or customer session. This special session object for customers holds all relevant information and provides a neat method to check if a customer is logged in: isLoggedIn(). It returns a boolean indicating logg in status of a Magento 2 customer. The following shows to methods on how to use this query:
Quick and dirty solution
Quick and dirty, because it uses a singleton instance of object manager.
1 2 3 4 5 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManager->get('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { // customer is logged in } |
I have already mentioned it and mention it again: try to avoid using object manager if you can. It slows down your shop.
Recommended solution
In my recommended solution I inject customer session into my model and create a proper getter function. You can always do this for your model, helper or block classes.
1 2 3 4 5 6 7 8 9 10 11 12 | class MyClass { protected $customerSession; public function __construct(\Magento\Customer\Model\Session $customerSession) { $this->customerSession = $customerSession; } public isCustomerLoggedIn() { return $this->_customerSession->isLoggedIn(); } } |
You can add this to any class you have. With isCustomerLoggedIn() function you get correct status for current user on site. If it is a guest customer, or the customer is not logged in already, this will return false.
Conclusion
Magento 2 offers you a simple solution to find out if a customer is logged in or not. It is basically the same solution as in Magento 1, but you need to use special customer session object for this. You should inject this instead of using object manager.
Hi, I want to show the default welcome message only when the customer is logged in. Please help me to solve this. Thank you.
Very nicely written article! I wanted to point out one small typo in your post 🙂
public isCustomerLoggedIn() {
return $this->_customerSession->isLoggedIn();
}
should be:
public function isCustomerLoggedIn() {
return $this->_customerSession->isLoggedIn();
}
You simply forgot to add “function” to the function. Cheers!
Missing underscore in the class var too!
YAY! Another incomplete solution!