3

I want to get current customer id in Helper class of module in magento2.

How to get using helper in Magento 2.

Can anyone help me?

Prince Patel
  • 22,708
  • 10
  • 97
  • 119
Mohit chauhan
  • 840
  • 5
  • 15
  • I'm not 100% sure what you are trying to do, but more than likely your module will not work correctly once full page cache is enabled if you are trying to display page specific info. See https://magento.stackexchange.com/a/92133/519 and http://devdocs.magento.com/guides/v2.1/config-guide/cache/cache-priv-priv.html – MagePal Extensions May 12 '17 at 18:50

3 Answers3

3

app/code/Vendor/Module/Helper/Data.php

<?php

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_customerSession;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $customerSession
    ) 
    {
        $this->_customerSession = $customerSession; 
        parent::__construct($context);   
    }

    public function getCustomerId()
    {
        //return current customer ID
        return $this->_customerSession->getId();
    }
}

Then you can get this function in block or controller like this

.....
protected $_helper;
.....

public function __construct(
    .....
    \Vendor\Module\Helper\Data $helper
    .....
) 
{
    .....
    $this->_helper = $helper; 
    .....   
}

public function getCustomerData()
{
    //Print current customer ID
    echo $this->_helper->getCustomerId();

}
Prince Patel
  • 22,708
  • 10
  • 97
  • 119
0
<?php
    public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Customer\Model\Session $customerSession
) {
    $this->customerSession = $customerSession;
    parent::__construct(
        $context
    );
}

Now call inside function like below,

$customerId =  $this->customerSession->getId();
Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183
0

Refer Magento2 native code helper class in which inject the class Magento\Customer\Model\Session and fetch the current customer id as follow

$this->_customerSession->getCustomerId()

You can refer Magento2 native code vendor/magento/module-catalog/Helper/Data.php

Definitely, you will get your answer here.

SATISH A
  • 61
  • 1
  • 5