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.
You can load customer by ID using:
Let’s look at each one of them.
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);
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); } }
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.