How to determine whether a customer is logged in or not in Magento 2.
If the customer is logged in, how do you retrieve customer information from a session?
How to determine whether a customer is logged in or not in Magento 2.
If the customer is logged in, how do you retrieve customer information from a session?
You first need to inject the following class in your constructor: /Magento/Customer/Model/Session :
protected $_customerSession; // don't name this `$_session` since it is already used in \Magento\Customer\Model\Session and your override would cause problems
public function __construct(
...
\Magento\Customer\Model\Session $session,
...
) {
...
$this->_customerSession = $session;
...
}
Then in your class you can call the following:
if ($this->_customerSession->isLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}
In a template
It requires a bit more work in a template as you will have to setup a preference for the block that renders the template to do that the clean way:
<preference for="Block\That\Renders\The\Template"
type="Vendor\Module\Block\Your\Custom\Block" />
Then in your custom block contrusctor you need to following the same dependency injection as for any class (explained above).
The extra step here is to create a public method that can be used in your template to check whether a customer is logged in or not
public function isCustomerLoggedIn()
{
return $this->_customerSession->isLoggedIn();
}
Then in your template you can call:
if ($block->isCustomerLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}
Alternative if the customer session is not initialized yet
There's another way of doing it which implies using Magento\Framework\App\Http\Context instead of Magento/Customer/Model/Session
Then you can call $this->_context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH) instead of $this->_customerSession->isLoggedIn() to check whether the customer is logged in or not.