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;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductFactory $productFactory,
array $data = []
) {
$this->_productFactory = $productFactory;
parent::__construct($context, $data);
}
/**
* Get Product by id
*
* @param int $id
* @return \Magento\Catalog\Model\Product
*/
public function getProductById($id)
{
return $this->_productFactory->create()->load($id);
}
/**
* Get Product by sku
*
* @param string $sku
* @return \Magento\Catalog\Model\Product
*/
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;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
* @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 $id
* @return \Magento\Catalog\Model\Product
*/
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
/**
* Get Product by sku
*
* @param string $sku
* @return \Magento\Catalog\Model\Product
*/
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();
Leave A Comment