Magento 2: How to Check if a Customer is Logged in?
February 20, 2024
As Magento 2 store owner, you may want to treat logged in and non-logged in customers differently. For example, you may want to offer exclusive features or discounts to logged in customers only. To implement this, you first need to confirm whether a Magento 2 customer is logged in or not?
Methods To Check If A Customer Is Logged-In In Magento 2
There are 2 ways you can check this. By injecting class and by using object manager. Although the 2nd method (object manager) is not recommended, it’s still used as an alternative.
Method 1: By Injecting Class (Dependency Injection)
In this method, first, you need to inject the following class in the constructor method:
/Magento/Customer/Model/Session
protected $_session;
public function __construct(
...
\Magento\Customer\Model\Session $session,
...
) {
...
$this->_session = $session;
...
}
Then in your class, use the following code in any function to check if the customer is logged in or not:
if ($this->_session->isLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}
Sample Code:
<?php
namespace [Vendor]\[Module]\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Customer\Model\Session;
class ClassName extends Action {
protected $_session;
public function __construct(Context $context, Session $session) {
parent::__construct($context);
$this->_session = $session;
}
public function execute()
{
// by using Session model
if($this->_session->isLoggedIn()) {
//customer has logged in
// your code in here
}else{
//Customer is not logged in
// your code in here
}
}
}
Method 2: Using Object Manager
You can use this method as an alternative to the above.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
// customer login action
}