How to check if customer is logged in or not in magento 2?

  • 5 years-11 months

    How to check if customer is logged in or not in magento 2?

    • Category : magento
    • Viewed : 19 times
    • Posted On :
    • Posted by : Vikas

    Customer session does not work except some pages

    Method 1.  To check if customer is logged: (best way)
    Create helper file like Data.php

    how to create custom helper or module https://www.dorcode.com/blog/52/how-to-create-and-use-helpers-in-magento-2
     
    <?php
    namespace Magento\Mytheme\Helper;
    
    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        protected $_customerSession;
        protected $_customerSessionn;
    
        public function __construct(\Magento\Framework\App\Helper\Context $context,
                \Magento\Framework\App\Request\Http $request,
                \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
                \Magento\Customer\Model\SessionFactory $customerSession,
                \Magento\Customer\Model\Session $customerSessionn
            ) 
        {
            $this->request = $request;
            $this->customerRepository = $customerRepository;
            $this->_customerSession = $customerSession;
            $this->_customerSessionn = $customerSessionn;
            parent::__construct($context);
        }
        public function getCustomerName(){
            $customer = $this->_customerSession->create();
            return $customer->getCustomer()->getName();
        }
        public function isLoggedIn()
        {
            return $this->_customerSessionn->isLoggedIn();
        }
    }
    ?>
    
    Call to your template :
    
    <?php
    $myhelper = $this->helper('Magento\Mytheme\Helper\Data');
    $cname=$myhelper->getCustomerName();
    $isLoggedIn=$myhelper->isLoggedIn();
    
    if ($isLoggedIn):
    	   echo 'login';
    else : 
    	  echo 'not login';
    endif;
    ?>
    Method 2. To check the customer is logged or not on any page of the website:
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    
    $customerSession = $objectManager->get('Magento\Customer\Model\Session');
    
    if($customerSession->isLoggedIn()) {
    
       // customer login action
    
    }
     

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.