3

I tried this code but when cache is disable. it works, but when I enable cache it does not work.

$ObjectManager = \Magento\Framework\App\ObjectManager::getInstance();
$session =  $ObjectManager->get('Magento\Customer\Model\Session');
if($session->isLoggedIn()) 
{
}
  • in which file you are using this code? – Hitesh Vaghasiya Dec 21 '17 at 5:05
  • i created one custom file for My account link in Magento_Theme Folder – Kushal Dani Dec 21 '17 at 5:06
  • Magento discourages us to use Object Manager directly. – Khoa TruongDinh Dec 21 '17 at 5:24
3

Use below code:

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

The best practice is to use Magento\Framework\App\Http\Context to check the customer logged in or not. And, avoiding using Object Manager directly.

For example:

<?php

namespace Vendor\Customer\Block\Account;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\Http\Context as HttpContext;

class Customer extends Template
{
    /**
     * @var HttpContext
     */
    protected $httpContext;

    /**
     * @param Context $context
     * @param HttpContext $httpContext
     * @param array $data
     */
    public function __construct(
        Context $context,
        HttpContext $httpContext,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->httpContext = $httpContext;
    }

    /**
     * Checking customer login status
     *
     * @return bool
     */
    public function customerLoggedIn()
    {
        return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    }
}

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.