1

I am instantiating the customer session helper (\Magento\Customer\Model\Session $customerSession) correctly, but this function always returns false, even though the customer is logged in. What am I missing here?

3

If store cache is enable, you can not get customer session. Check below code for get customer session with enable cache.

/**
 * @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());
}

Write above code in block, It is working even cache is enable.

0

I solved the problem by adding cacheable=false for that block, in the layout .xml file.

0

Try this :

protected $_session;

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

public function isLoggedIn()
{
       if ($this->_session->isLoggedIn()) {
              // Customer is logged in 
        } else {
           // Customer is not logged in
        }
}

Note: This works for frontend customers only. So If you are checking in admin section then it won't work.

Thanks.

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.