Collecting information about products on Magento 2 is a bit tough. But with the right program, everything is easy and possible. Well, today's tutorial will help you with the step by step guide to get product collection by product ID in Magento 2. The below-mentioned code structure will help you through:
<?php namespace MageDelight\Training\Block; class Product extends \Magento\Framework\View\Element\Template { /** * Constructor * * @param \Magento\Framework\View\Element\Template\Context $context * @param array $data */ public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\API\ProductRepositoryInterface $productRepository, array $data = [] ) { $this->productRepository = $productRepository; parent::__construct($context, $data); } /** * Get Product by Id * @param int * @return \Magento\Catalog\Model\Product $product */ public function getProduct($id) { return $this->productRepository->getById($id); } }
Now call inside template file with below code:
$product_id = 1; $product = $block->getProduct($product_id); echo $product->getName(); // product name echo $product->getSku(); // product sku
We hope that we have cleared everything related to getting product collection by product ID in Magento 2. If we missed out anything, feel free to contact us.
Also read:
- How to Get Product Collection in Magento 2
- How to Get Recently Viewed Product Collection of a Customer in Magento 2
- How to Get Product Collection by Product SKU in Magento 2
- How to Get Related Products Collection in Magento 2
- How to Get Orders Collection between a Date Range in Magento 2
- How to Get Order Item Collection by Item ID in Magento 2