As we all know, there are so many cases where we need to check whether a customer is currently logged in or not on your website. For example, there are some special promotions for logged customers. Today, this blog will show you how to check a customers’ logging status in Magento 2.
In Magento, sessions play an important role in enhancing the user’s experience and they are also useful in gathering vital stats about the user’s visits. The feature of the session is to store information related to the user’s interaction on the server-side.
I recommend this solution for you:
Using Magento\Customer\Model\Session::isLoggedIn()
method.
isloggedIn()
method returns a boolean indicating log in the status of the customer. A guest customer or non-logged in customer browsing the site will return false, and vice versa.
To use this class in a controller, helper or an observer... you can follow these steps:
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 }
READ MORE. How to add custom columns to customer grid - Magenest Blog
Code sample using a controller class:
Replace [Vendor] and [Module] with your vendor and module name
<?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 } } }
We hope that this article will help you to check customer is logged in Magento 2. Happy coding!