4

If I used cacheable="false"in my custom module layout file then I get customer id by using when all type of cache is enabled.

public function _construct(
    \Magento\Customer\Model\Session $session
) {
    $this->customerSession = $session;
}
public function abc()
{
    if ($this->customerSession->isLoggedIn()) {
        echo $this->customerSession->getCustomerId();
    }
}

But when I upload module in the marketplace then it rejected because of cacheable="false" so what is alternative way of cacheable="false"to get customer id in the frontend.

2

Please use this code for your construct method.

public function _construct(
    \Magento\Customer\Model\Session $session
) {
    $this->_isScopePrivate = true;
    $this->customerSession = $session;
}
public function abc()
{
    if ($this->customerSession->isLoggedIn()) {
        echo $this->customerSession->getCustomerId();
    }
}
  • it is throwing varnish cache error & also deprecated method. – Himanshu Dec 22 '18 at 10:45
1

Use model factory instead of model class

public function _construct(
    \Magento\Customer\Model\SessionFactory $sessionFactory
    ){
         $this->customerSessionFactory = $sessionFactory;
    }
    public function abc(){
        $customerSession  = $this->customerSessionFactory->create();
        if($customerSession->getCustomer()->getId()){
            return $customerSession->getCustomer()->getId();
        }
    }

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.