5

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.

1
  • Working or not? Commented Jun 15, 2018 at 8:33

3 Answers 3

3

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();
    }
}
1
  • 2
    it is throwing varnish cache error & also deprecated method.
    – Himanshu
    Commented Dec 22, 2018 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();
        }
    }
0

One needs to implement Private Content mechanism as described in magento official documentation here :

https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cache/page-caching/private-content.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.