Magento 2 – How to Get Current Customer ID in Helper Class

customermagento2magento2.2

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?

Best Answer

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

}
Related Topic