:::: MENU ::::

Magento2 load Customer by Id

This tutorial is about Magento 2 Load Customer by Id. I assume the question arises is What is the best way to load Customer by Id?. And how can we do it?.Furthermore,there are different ways in magento 2, to do so.

Like we can do so using customer interface or customer factory.

Like i said there are many ways,But the best practice is to use service contracts.

Api Repository:

In my case i would use

\Magento\Customer\Api\CustomerRepositoryInterface

Similarly use the below code.

protected $_customerRepositoryInterface;
public function __construct(
    ....
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    ....
) {
    ....
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
}

Furthermore call this function in your code like:

$customerId = 1;
$customer = $this->_customerRepositoryInterface->getById($customerId);

Factory Method:

namespace QaisarSatti\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()
    {
        $customer_id=7;
        return $this->customer->create()->load($customer_id);
    }

}

Object Manager:

No recommended method to use in magento2 but so magento use it so here it is just for knowledge.

$customer_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerData = $objectManager->create('Magento\Customer\Model\Customer')->load($customer_id);

That’s it from this tutorial. I hope it serves the purpose.
Please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: November 18, 2018


So, what do you think ?