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?

1
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();

}
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();
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.

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.