How to check if customer is logged in or not?

18 Aug, 2021

Today I am going to show you how we can check customer is logged in or not on Magento 2

Two ways We can check customer is logged is or not.

1. Using Magento\Customer\Model\Session object

If you need to check in Controller, Block, Helper or Observer then please follow the code


    <?php 
    /* Your namespace and class declaration */

    protected $customerSession;

    /* add Magento\Customer\Model\Session to you constructor */
    public function __construct( 
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
    }


    /* 
    function for checking customer is logged in or not 
    this function return boolean.
    if customer is logged in then it's return true else return false
    */
    public function isCustomerLoggedIn()
    {
        return $this->customerSession->isLoggedIn();
    }

If you wan't to use in .phtml file then follow the code


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

?>

2. Using Magento\Framework\App\Http\Context object

If you need to check in Controller, Block, Helper or Observer then please follow the code


    <?php 
    /* Your namespace and declaration */

    protected $httpContext;

    /* add \Magento\Framework\App\Http\Context to you constructor */
    public function __construct( 
        \Magento\Framework\App\Http\Context $httpContext
    ) {
        $this->httpContext = $httpContext;
    }


    /* 
    function for checking customer is logged in or not 
    this function return boolean.
    if customer is logged in then it's return true else return false
    */
    public function isCustomerLoggedIn()
    {
        return $this->httpContext->isLoggedIn();
    }

If you wan't to use in .phtml file then follow the code


<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$httpContext = $objectManager->get("Magento\Framework\App\Http\Context");
if($httpContext->isLoggedIn()) {
   // customer login action
}

?>

RAJU SADADIYA (MAGENTO DEVELOPER)