Tutorialsplane

Magento 2 Get Current Customer Id


Magento 2 Get Current Customer Id It very common we need to get the current customer’s detail. The way to get the current customer detail is different than the mangento 1. Here in this tutorial we are going to explain how you can get current customer id in Magento 2.


Magento 2 Get Current Customer Id Example

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 block, model or helper using the above method.

Other Method

You can also use object manger 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
      }