top of page

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);

Recent Posts

See All

Comentarios


Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

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

bottom of page