Magento 2 Product Load by ID

The purpose of loading products is the most sought after tool by many merchants as it happens to be useful to get product information. It allows one to make changes to the information and/or do other things with the help of the ID assigned to the particular product.

Listed below are 3 simple ways you can load products from their ID’s with the help of simple codes recommended by Magento.

How to Load a Product by ID in Magento

There are 3 different ways to do so:

  • By Factory
  • By Object
  • By API Repository

By Factory

By default Magento 2’s way of getting products and other models is by factory. It represents an all-new design pattern that can be implemented in the shop software.

Below are the codes you can use to get a product through factory in Magento 2:

class Product extends \Magento\Framework\View\Element\Template
  protected $_product;  
  public function __construct(
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {
        $this->_productloader = $_productloader;
    public function getLoadProduct()
        return $this->_productloader->create()->load($product_id);

To get a product by ID, utilize the following command:

	$product = $this->_productloader->create()->load($id);

By Object

The second option that you can use is a process from the time of Magento 1; product by ID using the object method. You will require an object manager instance which will be easily available everywhere as it’s a singleton class. It is highly recommended to save this instance in your __construct method which will help you reduce the number of code lines.

Here are the codes to get a product by ID using the object method:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);

By API Repository

Another approach that is not represented in 1.x is based on repositories. They introduce another design pattern that can be utilized to get objects. Use the following code snippet to get product objects:

Lastly, you can use this approach which is based on repositories and is not represented in 1.x. This gives you access to another design pattern that can easily be used to get objects.

Below is the code that will help you get the product objects:

protected $_productRepository;
    public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->_productRepository = $productRepository;

And you can get the product by ID using this code:

$product = $this->_productRepository->getById($id);
Avail The Opportunity

Subscribe to Our Updates and Newsletters.