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

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

  • none of the solution mentioned here worked for me. @Rakesh : could you share how it worked for you? – Ipsita Rout Jul 27 '16 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 '16 at 4:02
  • @Rakesh, Coul you please check these, magento.stackexchange.com/questions/185994/… ,, magento.stackexchange.com/questions/186036/… – Jsparo30 Jul 23 '17 at 14:51
  • 1
    What the below line is doing ? var isLoggedIn = $('.authorization-link > a').attr('href').indexOf('/login')<0; – Jaisa Dec 27 '17 at 10:51
  • Check link, rakeshjesadiya.com/… – Rakesh Jesadiya Aug 9 at 17:06

15 Answers 15

up vote 42 down vote accepted

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

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}
  • 1
    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. – Mage2.PRO Nov 28 '15 at 15:15
  • 10
    One should not use objectmanager directly. Simply inject the ObjectFactory generated code for the session model. – CarComp Apr 13 '16 at 12:44
  • 5
    please don't copy other answers in your answer. – Marius Jul 15 '16 at 14:31
  • I don't copy answer from other. I just updated this for current version. – Sohel Rana Jul 15 '16 at 14:45
  • 5
    this is the "wrong" way, the answer from Raphael at Digital Pianism is the rigth one – Lorenzo Nov 14 '16 at 9:23

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 $_session;

public function __construct(
    ...
    \Magento\Customer\Model\Session $session,
    ...
) {
    ...
    $this->_session = $session;
    ...
}

Then in your class you can call the following:

if ($this->_session->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->_session->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->_session->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

  • 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 '16 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 – Raphael at Digital Pianism Aug 11 '16 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 '16 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). – Vladimir Despotovic Mar 31 '17 at 9:18
  • @VladimirDespotovic did you test the alternative method ? – Raphael at Digital Pianism Mar 31 '17 at 9:45

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

  • HTTP context is initialized earlier than customer session (but it does not matter since both are initialized in action controllers)
  • When PageCache module is on (probably always on production), keep in mind that as soon as layout generation started, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. It means that if you now check if customer is logged in via HTTP context, it will still say 'yes', but customer data will not be available in customer session anymore. So double check is necessary before trying to access data in customer session. This can easily happen in 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 instance of ResultInterface

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

  • great hint for PageCache enabled, thx – LucScu May 4 '17 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? – Nitesh Jun 13 '17 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. – Ligemer Nov 13 '17 at 21:00
  • 2
    why do you have to put cachable = false? – LucScu Jan 23 at 10:48
/** @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);
  • so how get custommer is login @Mage2.PRO ? – xanka Dec 6 '15 at 8:08
  • 6
    You should never use ObjectManager directly – 7ochem Jul 15 '16 at 11:14
  • Yes, agreed. Objectmanager is not the way to go. Inject the CustomerFactory in the class constructor. – CarComp Jul 15 '16 at 11:56
  • The above solution doesnt work for me – Ipsita Rout Jul 28 '16 at 14:51
  • @lpsita Let me know if you have this issue? I just fixed it :) – Jai Jun 9 '17 at 10:52

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; ?>

Hope it helps

  • Nice solution without using objectmanager. – Nitesh Apr 20 '17 at 13:01
  • 2
    This did not work in v2.1.5 with FPC and Varnish enabled in production mode. – thdoan Apr 27 '17 at 4:18

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 (carl@partfire.co.uk)
 * 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
}
  • That's true, the only code that worked on me is yours. Thank you! – George George Apr 4 '17 at 22:47
  • How can I call ->getCustomer()->getName() using the context, because If I use the Session is not working for all pages. – George George Apr 5 '17 at 1:59
  • Thanks! At last, this works for me. – Amrit Pal Singh Oct 11 at 8:20

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
    If you get an error for the factories, then use the full path, e.g. \Magento\Customer\Model\SessionFactory $sessionFactory. – thdoan Apr 27 '17 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 '17 at 18:55

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.

  • It is a good solution. Though you can use cachable="false" in layout file. – Dinesh Yadav Apr 27 '17 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 '17 at 5:37

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');
  • 4
    You should never use ObjectManager directly – 7ochem Jul 15 '16 at 11:13
  • This works only if cache is disable not in enabled-cache. – Jai Jun 9 '17 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 '17 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} – Jai Jun 9 '17 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 – Jai Jun 9 '17 at 9:52

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;
    }
}

Hello Guys i am trying to check the condition user logged in or not in mailto.phtml file.but its not working for me could you anyone please me

My code is here.

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php $_product = $block->getProduct() ?>
<?php if ($block->canEmailToFriend()): ?>
  <?php 
/** @var \Magento\Framework\App\ObjectManager $ */
$obm = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\Http\Context $context */
$context = $obm->get('Magento\Framework\App\Http\Context');
/** @var bool $isLoggedIn */
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn){ 
  $om = \Magento\Framework\App\ObjectManager::getInstance();
       $customerSession = $om->create('Magento\Customer\Model\Session');

       $suser_id = $customerSession->getCustomer()->getId();

            $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
            $connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
                $result1 = $connection->fetchAll(" SELECT * 
FROM  `mg1_customer_entity_varchar` WHERE `attribute_id` ='147' AND `entity_id` = '$suser_id'"); 
?>

   <a href="mailto:<?php /* @escapeNotVerified */ echo $result1[0]['value']; ?>"
       class="action mailto friend"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></a> <?php
}else{
  echo "not logged in".$isLoggedIn;
}
?>

<?php endif; ?>

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
    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 '16 at 11:13
  • 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 '16 at 11:57

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

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

if($customerSession->isLoggedIn()) {

}

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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