11

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();
}
  • 2
    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()' – Sohel Rana Aug 3 '16 at 17:48
  • I have logged in but it returns null. And I'm doing it in the block class. – Paul Aug 3 '16 at 17:50
  • Which session class you use? – Sohel Rana Aug 3 '16 at 17:51
  • I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why? – Paul Aug 3 '16 at 17:53
  • 4
    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class – Lukas Komarek Oct 18 '17 at 11:58
21

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();
    }
}
  • 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. – Paul Aug 3 '16 at 18:21
  • Finally, it works. I'm not sure what I have changed. – Paul Aug 5 '16 at 9:49
  • have you disabled full page cache maybe? – davideghz Mar 22 '17 at 8:32
  • 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"/> – Juliano Vargas Aug 9 '18 at 14:27
  • I disabled cache still its returning null – Ajwad Syed Aug 18 at 13:13
3

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

3

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>
  • 2
    this will cause the whole page and every page that use this block will be MISSed by the FPC – Doni Wibowo May 7 '18 at 9:47
  • @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 Oct 3 '18 at 15:03
1

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();
    }
}
  • 2
    Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference. – nshiff Apr 4 '17 at 15:22
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.

  • how to use cacheable="false" in cms pages? – jafar pinjar Mar 22 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();
}
0

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.

enter image description here

<?php
    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
    $storeManager  = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
    $storeID       = $storeManager->getStore()->getStoreId(); 
    $storeName     = $storeManager->getStore()->getName();
?>

<?php
    $customerSession = $om->get('Magento\Customer\Model\Session');
    if($customerSession->isLoggedIn()) {
            echo $customerSession->getCustomer()->getId(); // get ID
    }
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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