3

I'm calling the following helper but getCustomerId is returning NULL when I have cache enabled. If I disable all cache, then I can return the customer's ID.

<?php
namespace Company\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
  private $_customerSession;

  public function __construct (
    \Magento\Customer\Model\Session $customerSession
  ) {
    $this->_customerSession = $customerSession;
  }

  public function getCustomerId()
  {
    return $this->_customerSession->getCustomerId();
  }
}

I've also tried return $this->_customerSession->getCustomer()->getId(); which also returns NULL


Now if I inject the Object Manager instead, I get my desired result and it returns the customerId even with cache enabled:

...
public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectmanager
  ) {
    $this->_objectManager = $objectmanager;
  }

  public function isBrandingCustomer()
  {
    $customerSession = $this->_objectManager->create("Magento\Customer\Model\Session");
    return $customerSession->getCustomerId();
  }
...

So my question is, How can I return the customer's ID from $customerSession with cache enabled and without using Object Manager?

Your Answer

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

Browse other questions tagged or ask your own question.