Magento 2.x – Customer session not working – not getting customer logged in data
Hi there,
If you trying to get customer logged in data in your Magento 2 module, and for any reason this is not working, retriving null, or nothing ar all, this is mostly related with the enabled cache you are using.
To solve this out, you can proceed on two different ways.
Adding a piece of code in a block – even with cache enabled
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * @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()); } |
Add cacheable=”false” in your xml
1 2 3 |
<referenceContainer name="content"> <block class="Vendor\Modulename\Block\Customer" name="customer.session.data" template="Vendor_Modulename::customertab.phtml" cacheable="false" /> </referenceContainer> |
and below code would work directly on your block side:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/** * @var \Magento\Customer\Model\Session */ protected $_customerSession; /** * Construct * * @param \Magento\Framework\View\Element\Template\Context $context */ public function __construct(Template\Context $context, \Magento\Framework\App\Request\Http $request, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Customer\Model\Session $customerSession ) { $this->request = $request; $this->customerRepository = $customerRepository; $this->_customerSession = $customerSession; parent::__construct($context); } public function getOrderData(){ $customerId = $this->_customerSession->getCustomerId(); return $customerId; } |
Happy coding!!