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.
public function __construct(
....
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
....
) {
....
$this->_customerRepositoryInterface = $customerRepositoryInterface;
}
Furthermore call this function in your code like:
$customer = $this->_customerRepositoryInterface->getById($customerId);
Factory Method:
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.
$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.