• Bilal Malik

Get/Load product by id – Magento 2

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>
<?php 
$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);

#collection #product #repository

0 views

Recent Posts

See All

©2020 by Bilal Usean. Proudly created with Wix.com