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();
}
8 Answers 8
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();
 }
}
- 
 1I 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.fotfs– fotfs2016年08月03日 18:21:12 +00:00Commented Aug 3, 2016 at 18:21
- 
 Finally, it works. I'm not sure what I have changed.fotfs– fotfs2016年08月05日 09:49:49 +00:00Commented Aug 5, 2016 at 9:49
- 
 have you disabled full page cache maybe?davideghz– davideghz2017年03月22日 08:32:29 +00:00Commented Mar 22, 2017 at 8:32
- 
 1Yes 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"/>Juliano Vargas– Juliano Vargas2018年08月09日 14:27:25 +00:00Commented Aug 9, 2018 at 14:27
- 
 I disabled cache still its returning nullAjwad Syed– Ajwad Syed2019年08月18日 13:13:27 +00:00Commented Aug 18, 2019 at 13:13
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>
- 
 5this will cause the whole page and every page that use this block will be MISSed by the FPCYohanes Pradono– Yohanes Pradono2018年05月07日 09:47:43 +00:00Commented 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.Radu– Radu2018年10月03日 15:03:43 +00:00Commented 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 ?Nagasaki– Nagasaki2023年05月04日 13:13:59 +00:00Commented May 4, 2023 at 13:13
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
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();
 }
}
- 
 2Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.nshiff– nshiff2017年04月04日 15:22:35 +00:00Commented Apr 4, 2017 at 15:22
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.
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
 }
?>
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.
- 
 how to use cacheable="false" in cms pages?Jafar Pinjar– Jafar Pinjar2019年03月22日 07:20:32 +00:00Commented Mar 22, 2019 at 7:20
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();
}
$this->session->isLoggedIn()return true in my controller class but return false in my block class. Why?cacheable=falsesee Magento 2 - Get customer ID from session in a block class