Magento 2 is a powerful and versatile platform that allows merchants to perform a variety of tasks, including load customer by ID. 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.
Store owners need to be familiar with the various ways to load customer by ID because:
Manually looking up the customer data each time is time-consuming and outright frustrating. It can easily prevent admins to lose track of business-critical tasks. Naturally, faster access to customer data allows for quick decision-making and improvements in overall administrative processes. Suppose a customer has made a complaint or a query. By loading customer data by ID, the support team can quickly rectify the issue.
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.
This blog was created with FME's SEO-friendly blog