Faisal Shabir Jan
Faisal Shabir Jan

Reputation: 13

Get Customer Session without using cacheable="false" in Magento2

I am trying to get customer session data (private data) from session and show on frontend on one of the block. Due to personalization, i am not getting the data when the cache is enabled. I looked for solutions to this and found that with cacheable="false" one can achieve to get customers private data from session with Cache enabled. But i realized that the whole page is kept out of cache because of this. Can anyone help me to get data in a particular block without using cacheable="false" ?

Upvotes: 0

Views: 2425

Answers (2)

trilok kumar
trilok kumar

Reputation: 101

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customerSession = $objectManager->get('Magento\Customer\Model\Session');
    $customer = $objectManager->get('Magento\Customer\Model\Customer')->load($customerSession->getId());
    $cust_name =  '';
    $cust_email ='';
    $cust_telephone ='';
    if($customerSession->isLoggedIn()) {
        $cust_name =  $customerSession->getCustomer()->getName();
        $cust_email = $customerSession->getCustomer()->getEmail();

        if(!empty($customer->getPrimaryBillingAddress())){
            $cust_telephone = $customer->getPrimaryBillingAddress()->getTelephone();
        }
    }

Upvotes: 0

Ankur Verma
Ankur Verma

Reputation: 1

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

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

By this way you can use the customer session without using the cachable="false"

Upvotes: 0

Related Questions