4

This is my code below

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

   if ($customerSession->isLoggedIn()) 

   {

       $customerSession->getCustomerId();  // get Customer Id
        $customerSession->getCustomerGroupId();
        $customerSession->getCustomer();
        $customerSession->getCustomerData();

   }

I'm facing a problem when full page cache is enable on disable it's working fine.

Rafael Corrêa Gomes
  • 13,309
  • 14
  • 84
  • 171
Unknown
  • 581
  • 7
  • 22

3 Answers3

14

You need to use the factory method when FPC is enabled.

By Factory Method :

/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSessionFactory;

public function __construct(
    ....
    \Magento\Customer\Model\SessionFactory $customerSessionFactory
    ....
) 
{
    ....
    $this->_customerSessionFactory = $customerSessionFactory;
    ....
}

public function getCustomerId(){
  $customer = $this->_customerSessionFactory->create();
  echo $customer->getCustomer()->getId();
}

By Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('\Magento\Customer\Model\Session');

echo $customerSession->getCustomerId();
Rafael Corrêa Gomes
  • 13,309
  • 14
  • 84
  • 171
Rohan Hapani
  • 17,388
  • 9
  • 54
  • 96
6

You can give a try to below code:

1). Using Object Manager

$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;

2). DI way

/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;

public function __construct(Template\Context $context,
    \Magento\Framework\App\Request\Http $request,
    \Magento\Customer\Api\CustomerRepositoryInterface       $customerRepository,
    \Magento\Customer\Model\SessionFactory $customerSession
) 
{
   $this->request = $request;
   $this->customerRepository = $customerRepository;
   $this->_customerSession = $customerSession;
   parent::__construct($context);
}

   public function getCustomerId(){
   $customer = $this->_customerSession->create();
   var_dump($customer->getCustomer()->getId());
}

It will work even FPC is enabled.

anonymous
  • 3,722
  • 3
  • 25
  • 67
1

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

\\Use create instead get in object manager

$customerSession = $objectManager->create('\Magento\Customer\Model\Session');

echo $customerSession->getCustomerId();