How to Get Logged in Customer Data in Magento 2

You can use \Magento\Customer\Model\Session to get the current customer id. First import this class to get the customer session, after this you will be able to get the customer session data. Here is an example how to get the customer id from customer session –

Magento 2 Get Current Customer Id Example:

<?php


namespace Tutorialsplane\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->resultPageFactory = $resultPageFactory;        
        $this->_customerSession = $customerSession;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }

    public function getCustomer(){
        echo $this->_customerSession->getCustomer()->getId(); //Get Current customer ID
        $customerData = $this->_customerSession->getCustomer(); //Get Current Customer Data
        print_r($customerData->getData());


    }
}
?>

In the above example we have created a simple controller method getCustomer() to get the customer details- $this->_customerSession->getCustomer()->getId(); will give you current customer id, You can also get customer’s other details $customerData->getData().

You can get the current customer details in blockmodel or helper using the above method.

Other Method

You can also use object manager to get the current logged-in customer detail. You can fetch the customer session data simply as below –

Get Customer Id, Email, Customer Group, And Name Example:

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $customerSession = $objectManager->get('Magento\Customer\Model\Session');
    if($customerSession->isLoggedIn()) {
        echo   $customerSession->getCustomer()->getId()."<br/>";  // get Customer Id
        echo   $customerSession->getCustomer()->getName()."<br/>";  // get  Full Name
        echo   $customerSession->getCustomer()->getEmail()."<br/>"; // get Email Name
        echo   $customerSession->getCustomer()->getGroupId()."<br/>";  // get Customer Group Id
      }  

After run this command php bin/magento setup:upgrade && php bin/magento setup:static-content:deploy -f

Leave a comment

Your email address will not be published. Required fields are marked *