How to get customer data by customer id in Magento 2?

 In Magento blog

How can we get the customer data from id, not from customer session in Magento 2?

you can get customer addresses by ID in Magento 2 store

<?php

namespace Vender\Module\Block 

class Customer extends \Magento\Framework\View\Element\Template
{
    protected $customerRepository;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterfaceFactory $customerRepositoryFactory
	) {
        $this->customerRepository = $customerRepositoryFactory->create();
	}

    public function LoadCustomerById($customerId) {
         $customer = $this->customerRepository->getById($customerId);
         return $customer;
    } 
}
?>

You can get customer data by just using the customer id using the below code.

<?php
$customerId = 1; //pass dynamic customer id
$customer = $block->LoadCustomerById($customerId);
echo $customer->getFirstname();  // result customer first name
echo $customer->getEmail(); // result as customer email 
echo $customer->getLastname(); // customerr lastname
?>

You can get customer data by customer id using Object Manager.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerId = 1; //pass dynamic customer id
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
$email = $customer->getEmail();
?>

Leave a Comment

0