We can get product collection in different ways in Magento 2.

Get product by id using product repository

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

In phtml we can call like

<h3>Get product by id #1</h3>
$product = $block->getProductById(1);
echo __($product->getName());

Product repository getById method will accept the below arguments

public function getById($productId, $editMode = false, $storeId = null, $forceReload = false);


About Bilal

I'm a software programmer, I handle Magento2 modifications at any level.

View all posts by Bilal →

Leave a Reply

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