We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
How To Get Current Customer In Magento 2?
To get the current customer in Magento 2, you can use the
Magento\Customer\Model\Session
class, which holds the current customer's session data. Here's how you can do it:
1. Using Customer Session in a Block:
<?php namespace Vendor\Module\Block; use Magento\Framework\View\Element\Template; use Magento\Customer\Model\Session as CustomerSession; class CustomBlock extends Template { protected $customerSession; public function __construct( Template\Context $context, CustomerSession $customerSession, array $data = [] ) { $this->customerSession = $customerSession; parent::__construct($context, $data); } public function getCurrentCustomer() { return $this->customerSession->getCustomer(); } }
2. Using Customer Session in a Controller:
<?php namespace Vendor\Module\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Customer\Model\Session as CustomerSession; class Index extends Action { protected $customerSession; public function __construct( Context $context, CustomerSession $customerSession ) { $this->customerSession = $customerSession; parent::__construct($context); } public function execute() { $customer = $this->customerSession->getCustomer(); // Now you can use $customer for your logic } }
3. Using Customer Session in a Helper:
<?php namespace Vendor\Module\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Customer\Model\Session as CustomerSession; class Data extends AbstractHelper { protected $customerSession; public function __construct( \Magento\Framework\App\Helper\Context $context, CustomerSession $customerSession ) { $this->customerSession = $customerSession; parent::__construct($context); } public function getCurrentCustomer() { return $this->customerSession->getCustomer(); } }
Notes:
- The
getCustomer()
method will return an instance ofMagento\Customer\Model\Data\Customer
which contains customer data like first name, last name, email, etc. - Make sure that the customer session is initialised. If you try to get the current customer in an area where the session is not initialised (like in some backend or API contexts), this approach may not work.