Get/Load product by id – Magento 2
- Bilal Malik
- Jun 30, 2019
- 1 min read
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);
Comentarios