80

How to find if a customer is logged in or not in Magento 2.

If the customer is logged in then how to get customer data from a session?

5
  • none of the solution mentioned here worked for me. @Rakesh : could you share how it worked for you? Jul 27, 2016 at 14:29
  • Keep in mind that if you ever need to check logged in status from within a Magento JS module (text/x-magento-init), then you can save some overhead by avoiding ObjectManager instantiation and passing the status to the module's config object, and instead query for the login link from within the JS module, e.g.: var isLoggedIn = $('.authorization-link > a').attr('href').indexOf('/login')<0;
    – thdoan
    Oct 12, 2016 at 4:02
  • @Rakesh, Coul you please check these, magento.stackexchange.com/questions/185994/… ,, magento.stackexchange.com/questions/186036/…
    – Jsparo30
    Jul 23, 2017 at 14:51
  • 1
    What the below line is doing ? var isLoggedIn = $('.authorization-link > a').attr('href').indexOf('/login')<0;
    – Jaisa
    Dec 27, 2017 at 10:51
  • Check link, rakeshjesadiya.com/… Aug 9, 2018 at 17:06

22 Answers 22

81

Following code you can check customer login or not anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

From controller

$customerSession = $this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}
10
  • 2
    Of course, it is the most evident solution, and I employed it first time, but then I noticed that it does not work correctly when the customer session is not initialized yet, so I have found a less evident but more sustainable solution. Nov 28, 2015 at 15:15
  • 18
    One should not use objectmanager directly. Simply inject the ObjectFactory generated code for the session model.
    – CarComp
    Apr 13, 2016 at 12:44
  • 6
    please don't copy other answers in your answer.
    – Marius
    Jul 15, 2016 at 14:31
  • 7
    this is the "wrong" way, the answer from Raphael at Digital Pianism is the rigth one
    – Lorenzo
    Nov 14, 2016 at 9:23
  • 1
    If you have enabled full page cache and you call this in block/template, it doesn't work as customer session will always return empty. Use http context to check it instead.
    – leo
    Jun 18, 2018 at 9:02
113

Important reminder: One should never call the Object Manager directly

Thus here's how to do it the clean way

In any class except templates

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.

However this method may give you different results, I suggest you read this great answer for more information: https://magento.stackexchange.com/a/92133/2380

10
  • Where should be placed the <preference ... /> tag within a custom theme? What are exactly Block\That\Renders\The\Template and Vendor\Module\Block\Your\Custom\Block?
    – Andrea
    Aug 11, 2016 at 20:25
  • @Andrea well it depends and it's different for each case. That's why I used generic class path names in my answer Aug 11, 2016 at 20:52
  • I have a custom block defined as class Html extends \Magento\Framework\View\Element\Template where I can inject the session object in the constructor. I use this block within my custom theme in this way (from layout xml files): <block class="Vendor\ThemeName\Block\Html" template="Vendor_ModuleName::html/my-custom-template.phtml"/>. I would like to check the logged user within the template file my-custom-template.phtml. How should I use the `<preference .../> tag?
    – Andrea
    Aug 11, 2016 at 21:18
  • Doesn't work for me the ->isLoggedin() method. I don't know why but it never returns that customer is logged in, and it actually is! It is logged in (I am logged in). Mar 31, 2017 at 9:18
  • 2
    I had to call the variable $_customerSession instead of $_session. It seems that when extending Magento\Framework\View\Element\Template the variable $_session is already used for \Magento\Framework\Session\SessionManagerInterface in AbstractBlock. So first I got the error Invalid method Magento\Framework\Session\Generic\Interceptor::isLoggedIn(Array (...) Oct 4, 2017 at 14:46
44

It is possible via Magento\Framework\App\Http\Context or via Magento\Customer\Model\Session. However, the result may be different:

  • HTTP context is initialized earlier than the customer session (but it does not matter since both are initialized in action controllers)
  • When the PageCache module is on (probably always on production), keep in mind that as soon as layout generation started, the customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. It means that if you now check if the customer is logged in via the HTTP context, it will still say 'yes, but customer data will not be available in customer sessions anymore. So double-check is necessary before trying to access data in customer sessions. This can easily happen in the block, while is unlikely in action controller since you are not expected to generate layout manually there, it will be generated after-action controller returns an instance of ResultInterface

To eliminate any risk of described inconsistencies when PageCache is on, consider using customer session if it is already initialized (true for action controllers). Else use the HTTP context.

4
  • great hint for PageCache enabled, thx
    – LucScu
    May 4, 2017 at 14:25
  • 3
    @Alex I am using below code $customerSession = $objectManager->get('Magento\Framework\App\Http\Context'); $isLoggedIn = $customerSession->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH); But due to cache enable It showing Sign In option instead of Sign Out to logged in customer. How should I fix this? Jun 13, 2017 at 9:20
  • This bit us in the arse, thank you. Your answer needs more attention :-) The cache being enabled in production makes session difficult. Put cachable = false in the XML file of the route if you're writing custom magento plugins.
    – akahunahi
    Nov 13, 2017 at 21:00
  • 2
    why do you have to put cachable = false?
    – LucScu
    Jan 23, 2018 at 10:48
19

None of these solutions worked for me. Some pages would appear to be logged in but others would not. It seems this is the bug:

https://github.com/magento/magento2/issues/3294

I ended up creating a helper which I could call in my templates:

<?php
namespace MyVendor\MyModule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

/**
 * Created by Carl Owens ([email protected])
 * Company: PartFire Ltd (www.partfire.co.uk)
 **/
class Data extends AbstractHelper
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Http\Context $httpContext
    ) {
        parent::__construct($context);
        $this->httpContext = $httpContext;
    }

    public function isLoggedIn()
    {
        $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
        return $isLoggedIn;
    }
}

Then I could use the helper in my templates like so:

<?php
$helper = $this->helper('MyVendor\MyModule\Helper\Data');

if ($helper->isLoggedIn()) {
    //show something
}
3
  • That's true, the only code that worked on me is yours. Thank you! Apr 4, 2017 at 22:47
  • How can I call ->getCustomer()->getName() using the context, because If I use the Session is not working for all pages. Apr 5, 2017 at 1:59
  • if full page cache is enabled this is the right answer. You can check customersession first and if that returns false you can do this Jan 3, 2019 at 12:23
17
/** @var \Magento\Framework\App\ObjectManager $om */
$om = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\Http\Context $context */
$context = $om->get('Magento\Framework\App\Http\Context');
/** @var bool $isLoggedIn */
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
7
  • so how get custommer is login @Mage2.PRO ?
    – xanka
    Dec 6, 2015 at 8:08
  • 9
    You should never use ObjectManager directly
    – 7ochem
    Jul 15, 2016 at 11:14
  • Yes, agreed. Objectmanager is not the way to go. Inject the CustomerFactory in the class constructor.
    – CarComp
    Jul 15, 2016 at 11:56
  • The above solution doesnt work for me Jul 28, 2016 at 14:51
  • @lpsita Let me know if you have this issue? I just fixed it :)
    – Jarnail S
    Jun 9, 2017 at 10:52
14

None of the solutions here worked for me reliably in Magento v2.1 with Full Page Cache and Varnish enabled in Production mode. I finally found a solution that worked 100% of the time with all caching enabled after getting the idea from vendor/magento/module-theme/view/frontend/templates/html/header.phtml. Here is my solution, which shows a "Sign In" link when the user is logged out and a "Sign Out" link when the user is logged in:

<li data-bind="scope: 'customer'">
  <!-- ko if: customer().firstname  -->
  <a href="<?php echo $this->getUrl('customer/account/logout'); ?>" style="display:none;" data-bind="style: {display:'inline'}"><?php echo __('Sign Out') ?></a>
  <!-- /ko -->
  <!-- ko ifnot: customer().firstname  -->
  <a href="<?php echo $this->getUrl('customer/account/login'); ?>" style="display:none;" data-bind="style: {display:'inline'}"><?php echo __('Sign In') ?></a>
  <!-- /ko -->
  <script type="text/x-magento-init">
  {
    "*": {
      "Magento_Ui/js/core/app": {
        "components": {
          "customer": {
            "component": "Magento_Customer/js/view/customer"
          }
        }
      }
    }
  }
  </script>
</li>

UPDATE: Since v2.1.5 this solution is no longer reliable. See issue 9156 for a solution.

2
  • It is a good solution. Though you can use cachable="false" in layout file. Apr 27, 2017 at 5:35
  • I have cachable="false" in layout XML for this block, but varnish is still caching it apparently. Not sure if this is a bug or not, but Knockout is a good way to circumvent this. The only downside is that there is a little delay before the Sign In/Out link shows up because of KO binding.
    – thdoan
    Apr 27, 2017 at 5:37
13

To get user logged in at template, you can simply call helper in just one single line :

<?php $_loggedin = $this->helper('Magento\Checkout\Helper\Cart')->getCart()->getCustomerSession()->isLoggedIn(); ?>

<?php if( $_loggedin ) : ?>

     <div><!-- add your code --></div>

<?php endif; ?>
3
  • Nice solution without using objectmanager. Apr 20, 2017 at 13:01
  • 3
    This did not work in v2.1.5 with FPC and Varnish enabled in production mode.
    – thdoan
    Apr 27, 2017 at 4:18
  • How would you flip this around to check if the customer is NOT logged in? Apr 21, 2020 at 9:35
12

Another answer:

<?php $_loggedin = $block->getLayout()->createBlock('Magento\Customer\Block\Account\AuthorizationLink')->isLoggedIn() ?>
 <?php if( $_loggedin ) : ?>
   // your code
 <?php endif; ?>

What do you think?

1
  • 1
    its worked for me on phtml page
    – matinict
    Dec 8, 2020 at 6:42
11

Fetching the logged status from Session model will not work in case you want to use it after enabling Magento default FPC cache, in that case, you should use SessionFactory instead.

Session is not initiated if FPC caching is enabled, details: https://github.com/magento/magento2/issues/3294#issuecomment-328464943

To solve this you have to use SessionFactory, for example:

/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSessionFactory;

public function __construct(
    ....
    \Magento\Customer\Model\SessionFactory $customerSessionFactory
    ....
) 
{
    ....
    $this->_customerSessionFactory = $customerSessionFactory;
    ....
}

public function getCustomerId(){
  $customer = $this->_customerSessionFactory->create();
  echo $customer->getCustomer()->getId();
}
3
  • This worked for me, also, if you want to check if customer has logged in, by your solution, use $customer->isLoggedIn()
    – fudu
    Feb 24, 2020 at 7:30
  • 1
    Finally. Something that works on Magento 2.4 with FPC enabled. Thank you!
    – web master
    Apr 29, 2021 at 16:01
  • this is work on Magento 2.4, Thanks
    – mrfizh
    Aug 30, 2021 at 17:30
7

There are a lot of answers out there that go something like this...

GET OBJECT MANAGER LOAD UP CLASS MODEL DO STUFF

This is the WRONG methodology to use in Magento2.0. In 2.0, the auto generated object factories are the way to go. You can inject them into your constructor in almost any class and use them. Example:

public function __construct(
            Context $context,
            CollectionFactory $cmspageCollectionFactory,
            array $data = [],
            CustomerFactory $customerFactory,
            SessionFactory $sessionFactory)
        {
            parent::__construct($context, $data);
            $this->_cmspageCollectionFactory = $cmspageCollectionFactory;
            $this->customerFactory = $customerFactory;
            $this->sessionFactory = $sessionFactory;
        }

        /**
         * @return \Stti\Healthday\Model\ResourceModel\Cmspage\Collection
         */
        public function getCmspages()
        {
            // First check to see if someone is currently logged in.
            $customerSession = $this->sessionFactory->create();
            if ($customerSession->isLoggedIn()) {
                // customer is logged in;
                //$customer = $this->customerFactory->create()->get
            }
2
  • 2
    If you get an error for the factories, then use the full path, e.g. \Magento\Customer\Model\SessionFactory $sessionFactory.
    – thdoan
    Apr 27, 2017 at 4:41
  • Correct. I usually declare them at the top, just so my methods don't look like a huge mess :)
    – CarComp
    Apr 28, 2017 at 18:55
6

I have get the best solution. It is based on authentication of customer. Some of the case customer session was not working, But every time my solution will work. Lets take a look.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Block\Account\AuthorizationLink');
if ($customerSession->isLoggedIn() == true) {
//your code.
} ?>

Thanks.

1
  • Great job! Thanks you. Nov 20, 2019 at 4:50
5

Hello got answer here :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()) {
    $customerSession->getCustomerId();  // get Customer Id
    $customerSession->getCustomerGroupId();
    $customerSession->getCustomer();
    $customerSession->getCustomerData();

    echo $customerSessionget->getCustomer()->getName();  // get  Full Name
    echo $customerSessionget->getCustomer()->getEmail(); // get Email
}

Source.

$customerSession = $objectManager->get('Magento\Customer\Model\Session');

Replaced get with create now works fine:

$customerSession = $objectManager->create('Magento\Customer\Model\Session');
7
  • 5
    You should never use ObjectManager directly
    – 7ochem
    Jul 15, 2016 at 11:13
  • This works only if cache is disable not in enabled-cache.
    – Jarnail S
    Jun 9, 2017 at 9:29
  • @Jai, this work for me in development and production as well. Please can you send me the steps to reproduce the issue ?
    – Manish
    Jun 9, 2017 at 9:32
  • I have to check if user is logged in or not. But below code works only in disabled cache $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManager->create('Magento\Customer\Model\Session'); if ($customerSession->isLoggedIn()) { //CODE}
    – Jarnail S
    Jun 9, 2017 at 9:51
  • In enable cached: It works only on custom-dashboard pages not in home-page and other pages of site. My question: magento.stackexchange.com/q/177964/29175
    – Jarnail S
    Jun 9, 2017 at 9:52
5

This is also one of the solution "Check whether the Customer is Logged in or not in Magento2"

Try below code:

 $om = \Magento\Framework\App\ObjectManager::getInstance();
 $context = $om->get('Magento\Framework\App\Http\Context');
 $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
 if($isLoggedIn){
      echo "Yes Customer loggedin";
      echo "<pre>";print_r($context->getData()); 
 }
3

Try below code:

<?php
namespace YourCompany\ModuleName\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context);
    }

public function isLoggedIn() // You can use this fucntion in any phtml file
    {
        return $this->customerSession->isLoggedIn();
    }
}

For using above code in phtml file you can call isLoggedIn() function as:

<?php $helper = $this->helper('YourCompany\ModuleName\Helper\Data'); ?>
<?php if($helper->isLoggedIn()) : ?>
    logged in
<?php else : ?>
    not logged in
<?php endif; ?> 

Hope this help thanks.

3
  • hi @Shubdham, its not working.. Mar 21, 2019 at 13:11
  • this is a neat solution. thanks
    – Ask Xah
    Aug 7, 2019 at 17:14
  • Yeah thanks hope it helps you. Aug 7, 2019 at 17:16
2

If you want to check customer logged in or not then use this code in phtml files,

$om = \Magento\Framework\App\ObjectManager::getInstance();
$appContext = $om->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $appContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn) {
    /** LOGGED IN CUSTOMER, this should work in template   **/
}
2
  • 2
    You should never use ObjectManager directly and you should never use this type of code in a template. You should create functionalities in your block class to manage this.
    – 7ochem
    Jul 15, 2016 at 11:13
  • 1
    Once you know how to do it correctly, you wonder how you ever manager to do it the other way at all!
    – CarComp
    Jul 15, 2016 at 11:57
1

Current worked solution (IMHO)

<?php

namespace My\Module\Helper\Data;

/**
 * @var \Magento\Framework\ObjectManagerInterface
 */
protected $objectManager;

/**
 * @var \Magento\Customer\Model\SessionFactory
 */
protected $customerSession;

/**
 * Class Data
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
         \Magento\Framework\ObjectManagerInterface $objectManager
    )
    {
        $this->objectManager   = $objectManager;
        $this->customerSession = $this->objectManager->create('Magento\Customer\Model\SessionFactory')->create();
    }

    /**
     * @return \Magento\Customer\Model\SessionFactory
     */
    public function getCustomerSession()
    {
       return $this->customerSession;     
    }

    /**
     * @return bool
     */
    public function isCustomerLoggedIn()
    {
        return ($this->getCustomerSession()->isLoggedIn()) ? true : false;
    }
}
1
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');

if($customerSession->isLoggedIn()) {

}
1

I suggest this solution which uses multiple fallbacks

...

private $appContext;
private $session;

public function __construct(
   \Magento\Framework\App\Http\Context $appContext,
   \Magento\Customer\Model\Session $session
   ...
) {
    ...

    $this->appContext = $appContext;
    $this->session = $session;

    ...
}

public function isLoggedIn()
{
    if (empty($this->session)) { return false; }
    if ($this->session->isLoggedIn()) { return true; }
    return $this->appContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

...
0

Declare \Magento\Customer\Model\SessionFactory in construct of your class.

protected $customerSession;

public function __construct(
    \Magento\Customer\Model\SessionFactory $customerSession
) {
    $this->customerSession = $customerSession;
}

public function isLoggedIn() // You can use this function in phtml file
{
    return $this->customerSession->create()->isLoggedIn();
}
0

just add this script in your phtml file if you want to check using JS and change code in your if else

<script type="text/javascript">
    require(['jquery'], function($){
        jQuery(document).ready( function() {
            var isLoggedIn = jQuery('.authorization-link > a').attr('href').indexOf('/login')<0;
            
            if(isLoggedIn){
                
            }else{
                
            }
        });
    });
</script>
0

In Magento 2, you can get customer data from a session if the customer is logged in by injecting the Magento\Customer\Model\Session class in your class constructor and then using the getCustomerData() method to retrieve the customer data.

Here's an example code snippet:

<?php
use Magento\Customer\Model\Session as CustomerSession;

class MyCustomClass
{
    protected $customerSession;

    public function __construct(CustomerSession $customerSession)
    {
        $this->customerSession = $customerSession;
    }

    public function getCustomerData()
    {
        if ($this->customerSession->isLoggedIn()) {
            $customerData = $this->customerSession->getCustomerData();
            // $customerData will contain an array of customer data
            // Example:
            $customerId = $customerData['customer_id'];
            $customerEmail = $customerData['email'];
            $customerFirstname = $customerData['firstname'];
            $customerLastname = $customerData['lastname'];
            // ...
        }
    }
}

In this example, we first check if the customer is logged in using the isLoggedIn() method. If the customer is logged in, we use the getCustomerData() method to retrieve an array of customer data, which includes the customer's ID, email, firstname, lastname, and other information.

You can then use this customer data as needed in your class.

Thanks !!

-1

I tried many ways found on google but none of the solution works. SO I checked the core functionality and created a php file to check a customer is logged in or not without using the Object Manager.



            /**
         * Customer session
         * Module created by Web Technology Codes
         * Developed by Vinay Sikarwar
         * @var \Magento\Framework\App\Http\Context
         */
        protected $session;

        /**
         * Registration constructor.
         * @param Context $context
         * @param array $data
         */
        public function __construct(
            Context $context,
                    \Magento\Framework\Session\Generic $session,
            array $data
        )
        {
                    $this->_session = $session;
                    parent::__construct($context, $data);
        }

            /**
         * Checking customer login status
         *
         * @api
         * @return bool
         */
        public function isCustomerLoggedIn()
        {
            return (bool)$this->getCustomerId()
                && $this->checkCustomerId($this->getId())
                && !$this->getIsCustomerEmulated();
        }
    }

For more info check it here http://blog.webtechnologycodes.com/customer-loggedin-check-magento2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.