Magento 2 check if customer logged in or not
Today we talk about how in Magento 2 check if customer logged in or not. This tutorial includes check if customer logged in or not.Magento 2 use the model session for storing the current customer session data like customer id, customer email, customer name and other customer information. You have to inject \Magento\Customer\Model\Session to get current customer session data. So let start with our example.
Dependency Injection
protected $_customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
//Get current group
echo $this->_customerSession->getCustomer()->getId(); // get customer id
echo $this->_customerSession->getCustomer()->getName(); // get customer Full Name
echo $this->_customerSession->getCustomer()->getEmail(); // get customer Email
else:
echo “no logged in”;
endif;
}
public function __construct(
\Magento\Customer\Model\Session $customerSession,
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
//Get current group
echo $this->_customerSession->getCustomer()->getId(); // get customer id
echo $this->_customerSession->getCustomer()->getName(); // get customer Full Name
echo $this->_customerSession->getCustomer()->getEmail(); // get customer Email
else:
echo “no logged in”;
endif;
}
Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()):
//Get current group
echo $this->_customerSession->getCustomer()->getId(); // get customer id
echo $customerSession->getCustomer()->getName(); // get customer Full Name
echo $customerSession->getCustomer()->getEmail(); // get customer Email
else:
echo “no logged in”;
endif;
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()):
//Get current group
echo $this->_customerSession->getCustomer()->getId(); // get customer id
echo $customerSession->getCustomer()->getName(); // get customer Full Name
echo $customerSession->getCustomer()->getEmail(); // get customer Email
else:
echo “no logged in”;
endif;
2 thoughts on “Magento 2 check if customer logged in or not”
Leave a Reply
You must be logged in to post a comment.
Great Post, will be helpful for the people of Magento Community, Thanks.
Thats great post