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.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply