Magento 2 Load Customer by ID (3 Ways That Actually Work)

Magento 2 Load Customer by ID (3 Ways That Actually Work)
This is another very important question when it comes to Magento operations. Store admins frequently want to fetch different products and customers details to perform certain operations on them. In this article, we will see how to load customer by id in Magento 2? So let’s get started.

3 Ways to Load Customer By ID in Magento 2

You can load customer by ID using:
  • Constructor Method (recommended)
  • Factory Method
  • Object Manager
Let’s look at each one of them.

1. Constructor Method

The best and recommended way to Load Customer by ID in Magento 2 is to use the Constructor method. Api Repository: \Magento\Customer\Api\CustomerRepositoryInterface Use the code below:
protected $_customerRepositoryInterface;
public function __construct(
 ....
 \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
 ....
) {
 ....
 $this->_customerRepositoryInterface = $customerRepositoryInterface;
}
Now call this function.
$customerId = 1;
$customer = $this->_customerRepositoryInterface->getById($customerId);

2. Factory Method

Use the following script to Load Customer by ID using Factory Method.
namespace Company\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

 protected $customer; 

 public function __construct(
 
 \Magento\Customer\Model\Customer $customer

 ) {
 $this->customer = $customer;
 }

 public function getLoadProduct()
 {
 $customerId=1;
 return $this->customer->create()->load($customerId);
 }
}

3. Magento 2 Load Customer By ID Using Object Manager

Although this method is not recommended, it provides an alternative solution. Use the following code to load Customer by ID using Object Manager in your Magento store.
$customerId=1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerData = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
This is all for this tutorial. We hope it serves the purpose. If you have any problem, question, or suggestion, please don’t hesitate to contact us.