How to get product by ID and SKU in Magento 2
In Magento 2 there are various ways to load product by ID or SKU. We will try to show them to you so that you can use any of them, which fits best to your requirement.
Load Product using Model
Product can be loaded using the Magento\Catalog\Model\Product model. We will use the factory of this model to get the new instance of the product. For the demo we are injecting this dependency in the block file. You can use this somewhere else as per your need.
<?php
namespace WebbyTroops\Catalog\Block;
class Product extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductFactory $productFactory,
array $data = []
) {
$this->_productFactory = $productFactory;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productFactory->create()->load($id);
}
public function getProductBySku($sku)
{
return $this->_productFactory->create()->loadByAttribute('sku', $sku);
}
}
Load Product using Repository
You can also load product using Magento\Catalog\Api\ProductRepositoryInterface repository. All you need to do is inject the dependency in the constructor and use its method get() and getById($id) to get products by SKU and ID.
<?php
namespace WebbyTroops\Catalog\Block;
class Product extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $_productRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
array $data = []
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
}
Get Product in template file
Using any of the above approach you can load the product data and use it in the template file in the following way.
$product = $block->getProductById(5); // To load by SKU use $block->getProductBySku('sku-test');
$sku = $product->getSku();
$name = $product->getName();
Categories
Download The Free E-book & Launch Your Brand Strategically
Download The Free E-book & Launch Your Brand Strategically
Share this post