How to Load Product by ID in Magento 2?

While developing a Magento 2 extension or custom functionality many times developers need to get product information by the product ID. In Magento 2 there are different methods are available to get product data. In this code snippet post, I will show you How to load product data by product ID in Magento 2?

1. By factory

<?php
namespace Vendor\Module\Block;

class ProductData extends \Magento\Framework\View\Element\Template
{
    protected $productFactory;  

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productFactory = $productFactory;
        parent::__construct($context);
    }
    public function getProductById($id)
    {
        return $this->productFactory->create()->load($id);
    }
}

2. By Repository

<?php
namespace Vendor\Module\Block;

class ProductData extends \Magento\Framework\View\Element\Template
{
    protected $productRepository;  

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }
    public function getProductById($id)
    {
        return $this->productRepository->getById($id);
    }
}

Now we can use below code in template(phtml) file to display product data.

<?php
// get product by id
$_product = $block->getProductById(1);

echo $_product->getId(); //Product ID
echo $_product->getName(); //Product Name
echo $_product->getSKU(); //Product SKU
echo $_product->getPrice(); //Product Price
Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *