
As you know, order management in Magento 2 is quite a demanding process. It calls for full attention to the details and the ability to make quick decisions. Especially when it comes to customer-related information.
Just like getting a current customer, you should know how to get customer data by customer ID in Magento. And this is exactly what you'll learn today.
There are a few methods to use, so we'll look at each of them in detail.
Post Contents [hide]
Get Customer Data by Customer ID Using Factory Method
The factory method is among the most common ones. So, the code below will help you to get customer data by customer ID:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerId = 1; $customer = $customerFactory->load($customerId); print_r($customer->getData()); echo $customer->getEmail() . PHP_EOL;
echo $customer->getFirstname(). PHP_EOL;
echo $customer->getLastname(). PHP_EOL;
Get Customer Data by Customer ID Using API Repository
API repository method can be applied in this case as well. Just use the following code:
protected $customerRepository; public function __construct(
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository) {
$this->customerRepository = $customerRepository;
} public function getCustomerById($customerId)
{
return $this->customerRepository->getById($customerId);
}
Get Customer Data by Customer ID Using Object Manager
Finally, the object manager method. Though it seems to be the easiest one, some complications may appear on the way. Yet the below code helps to get customer data by customer ID:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerRepository = $objectManager->get(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$customer = $customerRepository->getById(55);
echo $customer->getEmail() . PHP_EOL;
echo $customer->getFirstname(). PHP_EOL;
echo $customer->getLastname(). PHP_EOL;
Note: it's recommended to avoid the direct usage of the object manager since it tends to hide the real dependencies of the class.
As you can see, you have multiple options to choose from. Just go for the method you feel the most comfortable working with.
However, you shouldn't stop here. It might also be useful to learn how to get product by ID in Magento 2. This skill will certainly come in handy while operating Magento.