Magento 2 – Get current logged in customer details

In our previous blog we have explained you how to check whether a customer is logged in or not. Now in this blog we are going to explain you how to get the details of customer which is logged in. There are two ways of getting the dettails of logged in customer details:

1. By Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()) {

    echo 'Customer Id: ' . $customerSession->getCustomer()->getId() . '<br/>';

    echo 'Customer Name: ' . $customerSession->getCustomer()->getName() . '<br/>';

    echo 'Customer Email: ' . $customerSession->getCustomer()->getEmail() . '<br/>';

    echo 'Customer Group Id: ' .  $customerSession->getCustomer()->getGroupId() . '<br/>';

}

2. Dependency Manager

Second way to get the detail of logged in customer is by Dependency Manager. As we already let you know that the direct use of object manager is not a good practice. So try to use dependency manager way, in this we might need to inject the object of \Magento\Customer\Model\Session class in the constructor of our module’s block class and access it from the phtml file.

<?php

namespace Magewizz\Module_name\Block;

class Block_Name extends \Magento\Framework\View\Element\Template

{

    protected $_customerSession;

         

    public function __construct(

        \Magento\Framework\View\Element\Template\Context $context,

        \Magento\Customer\Model\SessionFactory $customerSession,

        array $data = []

    )

    {

        $this->_customerSession = $customerSession->create();

        parent::__construct($context, $data);

    }

     

    public function getLoggedinCustomerId() {

        if ($this->_customerSession->isLoggedIn()) {

            return $this->_customerSession->getId();

        }

        return false;

    }

    public function getCustomerData() {

        if ($this->_customerSession->isLoggedIn()) {

            return $this->_customerSession->getCustomerData();

        }

        return false;

    }

}

Now in your phtml file access this data by following way

$customerId = $block->getLoggedinCustomerId();

echo 'Customer Id: ' . $customerId;

$customerData = $block->getCustomerData();

if($customerData) {

    echo 'Customer Id: ' . $customerData->getId() . '<br/>';

    echo 'Customer Name: ' . $customerData->getName() . '<br/>';

    echo 'Customer Email: ' . $customerData->getEmail() . '<br/>';

    echo 'Customer Group Id: ' . $customerData->getGroupId() . '<br/>';

}

This is all about getting details of logged in cutomer. Hope this will help you.

Leave a Reply

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