I'm trying to create a piece of code to check if the customer is loggen in or not. I read not to use the objectmanager for that, but I don't know where to put which code.

What I need:

if customer is logged in { Go to my account } else { Login }

How can this be achieved?

I'm using Magento 2.2.6

  • where you want to check this? in controller ? Oct 9 '18 at 10:00
  • I need to do this in: app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml
    – n00bly
    Oct 9 '18 at 10:02
  • Please check my answer and let me know if not solve your question. Oct 9 '18 at 10:19

You can use the below code as below:

protected $_custSession;

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

//later in your code you can use it as below

if ($this->_custSession->isLoggedIn()) {
    // if customer is logged in 
} else {
    // if customer is not logged in

Since you are asking your question in phtml you can use the below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customSession = $objectManager->get('Magento\Customer\Model\Session');
if($customSession->isLoggedIn()) {
   // customer is logged in
  //customer is not logged in
  • 1
    Great! It's working :) I don't know if this is the best and only method to use but it's working at my side.
    – n00bly
    Oct 9 '18 at 11:10

You can make custom helper in and can call in app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml

like below:

$helper = $this->helper('Vendor\Module\Helper\Header'); and you can call like:


In Vendor\Module\Helper\Header Class you can make one method for check customer is logged in or not

                  namespace Vendor\Module\Helper;

            class Header extends 

public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Customer\Model\Session $customerSession
        ) {

    $this->_customerSession = $customerSession;

public function isCustomerLoggedIn(){
    return $this->_customerSession->isLoggedIn();


  • Hi Rutvee, I which file should I put which piece of code?
    – n00bly
    Oct 9 '18 at 11:07
  • make one file Vendor\Module\Helper\Header with above code which answered by me Oct 9 '18 at 11:08
  • and check in app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml using $helper = $this->helper('Vendor\Module\Helper\Header'); $helper->isCustomerLoggedIn(); Oct 9 '18 at 11:09
  • This same solution is posted all over the place and it simply does not work. No matter what, it returns as not logged in. Jul 17 '20 at 20:39

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