In this post I am going to explain how to load product by ID in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_productRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
array $data = []
)
{
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($productId)
{
return $this->_productRepository->getById($productId);
}Add below code snippet in template file.
// Your product ID $productId = 9; $productData = $block->getProductById($productId); echo $productData->getId() . '<br/>'; echo $productData->getName() . '<br/>'; echo $productData->getProductUrl() . '<br/>';
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
// Your product ID
$productId = 9;
$productData = $productRepository->getById($productId);
echo $productData->getId() . '<br/>';
echo $productData->getName() . '<br/>';
echo $productData->getProductUrl() . '<br/>';Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply