Magento 2 load product by id

Today we talk about how in Magento 2 load product by id. There are three way to get product load in magento 2. First Object Manager second factory Method and third one is Api Repository.

Factory Method:

Best practice method always use this method.

namespace QaisarSatti\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {


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

}

Api Repository:

This was introduce in Magento 2.1 by magento.

    namespace QaisarSatti\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $_productRepository;
       

          public function __construct(
         
            ProductRepositoryInterface $productRepository
          ) {
         

              $this->_productRepository = $productRepository;
          }
          public function getProduct()
          {
              $productId=7;
              return $product = $this->productRepository->getById($productId);
          }
      }

Object Manager:

No recommended method to use in magento2 but so magento use it so here it is just for knowledge.

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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply