Load customer by id magento 2 object manager

 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.

protected $_customerRepositoryInterface;
public function __construct(
    ....
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    ....
) {
    ....
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
}

Furthermore call this function in your code like:

$customerId = 1;
$customer = $this->_customerRepositoryInterface->getById($customerId);

Factory Method:

namespace QaisarSatti\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()
    {
        $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.

$customer_id=7;
$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.

Comments