21

How to get customer ID from session? I tried this but not work.

protected $_customerBonusPointFactory;
protected $_customerSession;
public function __construct(Session $customerSession, \Magento\Framework\View\Element\Template\Context $context) {
 $this->_customerSession = $customerSession;
 parent::__construct($context);
}
public function _prepareLayout() {
 var_dump($this->_customerSession->getCustomer()->getId());
 exit();
 return parent::_prepareLayout();
}
Himanshu
1,76618 silver badges34 bronze badges
asked Aug 3, 2016 at 17:38
8
  • 2
    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()' Commented Aug 3, 2016 at 17:48
  • I have logged in but it returns null. And I'm doing it in the block class. Commented Aug 3, 2016 at 17:50
  • Which session class you use? Commented Aug 3, 2016 at 17:51
  • 1
    I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why? Commented Aug 3, 2016 at 17:53
  • 4
    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class Commented Oct 18, 2017 at 11:58

8 Answers 8

41

It's working copy. You can compare with your block class. Here I use Form as block class

namespace Vendor\Module\Block;
class Form extends \Magento\Framework\View\Element\Template
{
 protected $customerSession;
 /**
 * Construct
 *
 * @param \Magento\Framework\View\Element\Template\Context $context
 * @param \Magento\Customer\Model\Session $customerSession
 * @param array $data
 */
 public function __construct(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Customer\Model\Session $customerSession,
 array $data = []
 ) {
 parent::__construct($context, $data);
 $this->customerSession = $customerSession;
 }
 public function _prepareLayout()
 {
 var_dump($this->customerSession->getCustomer()->getId());
 exit();
 return parent::_prepareLayout();
 }
}
answered Aug 3, 2016 at 18:10
7
  • 1
    I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine. Commented Aug 3, 2016 at 18:21
  • Finally, it works. I'm not sure what I have changed. Commented Aug 5, 2016 at 9:49
  • have you disabled full page cache maybe? Commented Mar 22, 2017 at 8:32
  • 1
    Yes it was cache I've had same issue <block class="Vendor\Block\Bla\Bla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/> Commented Aug 9, 2018 at 14:27
  • I disabled cache still its returning null Commented Aug 18, 2019 at 13:13
11

When You define block which use session You have to disable cache for it.

 <block class="Vendor\Module\Block\Index" name="Name"
 template="Vendor_Module::template/path.phtml" cacheable="false">
 </block>
answered Dec 5, 2017 at 12:15
3
  • 5
    this will cause the whole page and every page that use this block will be MISSed by the FPC Commented May 7, 2018 at 9:47
  • 1
    @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example. Commented Oct 3, 2018 at 15:03
  • This is the best solution for me that I found but I don't really like it. Is there a way to cache it for each customer independently ? Commented May 4, 2023 at 13:13
5

You need to inject \Magento\Customer\Model\Session $customerSession, class to get customer ID from customer session.

protected $_customerSession;
public function __construct(
 ...
 \Magento\Customer\Model\Session $customerSession,
 ...
) {
 ...
 $this->_customerSession = $customerSession;
 ...
}
public function getCustomer()
{
 echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID
 $customerData = $this->_customerSession->getCustomer(); 
 print_r($customerData->getData()); //Print current Customer Data
}

NOTE: You only get customer id if customer logged in and customer session initialized

answered Apr 26, 2017 at 9:11
0
2

It seems to work when you pass the Context object to the parent class before instantiating the customer session :

class History extends \Magento\Framework\View\Element\Template
{
 /**
 * @var Session
 */
 protected $_session;
 public function __construct(
 Template\Context $context,
 \Magento\Customer\Model\Session $session,
 array $data
 )
 {
 parent::__construct($context, $data);
 $this->_session = $session;
 }
 public function _prepareLayout()
 {
 var_dump($this->_session->getCustomerId());
 exit();
 return parent::_prepareLayout();
 }
}
answered Oct 7, 2016 at 15:19
1
  • 2
    Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference. Commented Apr 4, 2017 at 15:22
1

I struggled to get the customer ID returning even with the cacheable attribute set to false.

What worked for me was using httpContext as explained in this article: https://aureatelabs.com/magento-2/how-to-get-customer-session-data-when-a-cache-is-enabled-in-magento-2/

Seems like the best solution as it doesn't require you to switch off caching.

answered Nov 25, 2020 at 10:12
1

First, create an instance in header.phtml file as below and also if more than one store is available and one wants to get mail in only one of the stores.

<?php
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
 $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
 $storeID = $storeManager->getStore()->getStoreId(); 
 $storeName = $storeManager->getStore()->getName();
?>
<?php
 $customerSession = $objectManager->get('Magento\Customer\Model\Session');
 if($customerSession->isLoggedIn()) {
 echo $customerSession->getCustomer()->getId(); // get ID
 }
?>
Msquare
9,4627 gold badges30 silver badges71 bronze badges
answered May 31, 2019 at 8:17
0

While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.

Please use cacheable="false" for bloick in your layout :

<referenceContainer name="content"> 
 <block class="Arman\Test\Block\List" name="list" template="Arman_Test::list.phtml" cacheable="false"> 
 </block>
 </referenceContainer> 

In this case, Magento 2 ignore this page from caching.

answered May 16, 2018 at 5:37
1
  • how to use cacheable="false" in cms pages? Commented Mar 22, 2019 at 7:20
0

If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.

As getId method also calls getCustomerId method.

file : vendor/magento/module-customer/Model/Session.php

/**
 * Retrieve customer model object
 *
 * @return Customer
 * use getCustomerId() instead
 */
public function getCustomer()
{
 if ($this->_customerModel === null) {
 $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
 }
 return $this->_customerModel;
}
/**
 * Retrieve customer id from current session
 *
 * @api
 * @return int|null
 */
public function getCustomerId()
{
 if ($this->storage->getData('customer_id')) {
 return $this->storage->getData('customer_id');
 }
 return null;
}
/**
 * Retrieve customer id from current session
 *
 * @return int|null
 */
public function getId()
{
 return $this->getCustomerId();
}
answered Jan 16, 2019 at 10:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.