1

I have to check whether a customer is logged in or not. It only works for My account page and for the rest of the pages, it gives a null result. It was working before.

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

This code only works for My Account page, and for all other pages, it gives the empty result.

I tried this in my header.phtml as I need loggedIn condition in my header.phtml but it doesn't work.

 $om = \Magento\Framework\App\ObjectManager::getInstance();
 $context = $om->get('Magento\Framework\App\Http\Context');
 $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);

Still, this doesn't work in my header.phtml

What the issue, how to resolve it.

0

You can create a module with helper method.

In Vendor/Module/Helper/Data.php,

<?php
namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

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
    ) {
       $this->httpContext = $httpContext;                
       parent::__construct($context);
    }

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

}

In your .phtml file, you can call like this:

$custom_helper = $this->helper('Vendor\Module\Helper\Data');

var_dump($custom_helper->isLoggedIn());
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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