Black Friday Sale  -  25% Off On All Products   -    Coupon: FMEBF2017

How To Load Product By Id In Magento 2?

Many developers ask how to retrieve particular product information in Magento 2. Object manager and factory method are the two different ways to retrieve the product information. However, Magento recommends using the factory method to retrieve any product information. Whether you are developing an extension or a theme, avoid using the Object method as you may receive technical rejection while submitting your extension to the Magento marketplace.

Here in this blog, we will be sharing the both methods as in times developers have to go by the Objectmanager to retrieve product information. You can load a product by ID in Magento2 by using the following php code, whereas you can make use of the best PHP editors to save time and ensure error-free retrieval of product information.

Object Manager: Load Product By Id in Magento2

This is a short method and its is not recommended by Magento.

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

Factory Method: Load Product By Id in Magento2:

This is a proper method recommended by Magento.

<?php
namespace FME\Module\Block;

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

  protected $_productloader;  


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

    ) {


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

}
 

phtml file code

$product=$this->getLoadProduct(20);
echo $product->getName();