How to get current customer id in helper class of module in magento2
-
08-10-2020 - |
Question
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?
Solution
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();
}
OTHER TIPS
<?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();
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange