How can i check if the customer has logged in to the magento and get the customer details like id, first name, last name, etc.,
I have tried this in 2 ways
1). Using the session in a block as below
protected $_session;
protected $_context;
public function __construct(
\Magento\Customer\Model\Session $session,
\Magento\Framework\View\Element\Template\Context $context
) {
parent::__construct($context);
$this->_session = $session;
}
public function isCustomerLoggedIn()
{
return $this->_session->isLoggedIn();
}
public function getCustomerId(){
return $this->_session->getCustomer()->getId();
}
call to the function isCustomerLoggedIn() gives boolean false and call to getCustomerId() returns NULL.
2). Using Object Manager in layout
$om = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $om->create('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
$customerSession->getCustomer()->getId();
$customerSession->getCustomer()->getName();
$customerSession->getCustomer()->getEmail();
$customerSession->getCustomer()->getGroupId(); // get Customer Group Id
}
This way gave the customer Id, Name, Email, Group Id of the previous logged in customer but not the current customer.
Can any one help to get the currently logged in customer details.
$customerSession = $om->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { $customerSession->getId(); }
Remove this getCustomer() $customerSession->getCustomer()->getId(); replace with $customerSession->getId();
– Kamal Jain Apr 07 '20 at 08:02