Milind Daraniya

How to Load Product by Product ID and SKU in Magento 2?

Published June 20th, 2023 2 min read

We will be looking into how you can load product from product ID and SKU both with the help of some simple codes that are also recommended by Magento.

Let’s first look at how you can load products from product ID.

Method – 1:

<?php
namespace Vendor\Extension\Block;

class Product extends \Magento\Framework\View\Element\Template
{
   protected $productrepository;  

   public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productrepository) {
        $this->productrepository = $productrepository;
   }

   public function getProductDataUsingId($productid) {
       return $this->productrepository->getById($productid);
   }
}

PHTML file code,
$product = $block->getProductDataUsingId(50);
echo $product->getName();

Method – 2: 

$productid = 50;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productid);

How to load products by product SKU ::

Method – 1:

<?php 
namespace Vendor\Extension\Block; 

class Product extends \Magento\Framework\View\Element\Template
{
  protected $productrepository; 

  public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productrepository) { 
         $this->productrepository = $productrepository;
  }

  public function getProductDataUsingSku($productsku) {
        return $this->productrepository->get($productsku);
  }
}


PHTML file code,
$product = $block->getProductDataUsingSku(“productsku”);
echo $product->getName();

Method – 2:

$productsku = "productsku";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->get($productsku);

Using these codes, you will be able to load product information by ID or SKU.

Thanks.