How to get customer by ID in Magento 2

In Magento 2 there are multiple ways to load customer data by ID. The code snippets below will help you to achieve it.

Load Customer using Model

Customer can be loaded using the Magento\Customer\Model\Customer model. We will use the factory of this model to get the new instance of the customer. We are injecting this dependency in the block file you can use this somewhere else as per your need.

<?php

namespace WebbyTroops\Customer\Block;

class Customer extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $_customerFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Customer\Model\CustomerFactory $customerFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        array $data = []
    ) {
        $this->_customerFactory = $customerFactory;
        parent::__construct($context, $data);
    }

    /**
     * Get Customer by id
     * 
     * @param int $id
     * @return \Magento\Customer\Model\Customer
     */
    public function getCustomerById($id)
    {
        return $this->_customerFactory->create()->load($id);
    }
}

Load Customer using Repository

You can also load customer using Magento\Customer\Api\CustomerRepositoryInterface repository. All you need to do is inject the dependency in the constructor and use its method getById($id) to get customer data by its ID.

<?php

namespace WebbyTroops\Customer\Block;

class Customer extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface
     */
    protected $_customerRepository;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        array $data = []
    ) {
        $this->_customerRepository = $customerRepository;
        parent::__construct($context, $data);
    }

    /**
     * Get Customer by id
     * 
     * @param int $id
     * @return \Magento\Customer\Model\Customer
     */
    public function getCustomerById($id)
    {
        return $this->_customerRepository->getById($id);
    }
}

Get Customer in template file

You can get customer data by its ID using any of the above pattern and use its data in template file in the following way.

$customer = $block->getCustomerById(12);
$email = $customer->getEmail();
$firstName = $customer->getFirstName();

Leave A Comment

Go To Top