Magento2: How to load product by id code example
Example 1: magento load product by id
$productId = 20;
$product = Mage::getModel('catalog/product')->load($productId);
Example 2: Magento2: How to load product by id
<?php
namespace Test\Module\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productloader;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
parent::__construct($context);
}
public function getLoadProduct($id)
{
return $this->_productloader->create()->load($id);
}
}
Example 3: Magento2: How to load product by id
<?php
namespace Test\Module\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $productRepository;
protected $_storeManager;
public function __construct(
\Magento\Framework\App\Action\Context $context,
ProductRepositoryInterface $productRepository
) {
parent::__construct($context);
$this->productRepository = $productRepository;
}
public function getProduct()
{
$productId=1;
return $product = $this->productRepository->getById($productId);
}
}
Example 4: Magento2: How to load product by id
$product=$this->getLoadProduct(20);
echo $product->getName();
Example 5: Magento2: How to load product by id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);