Magento 2 load product by id
Today we talk about how in Magento 2 load product by id. There are three way to get product load in magento 2. First Object Manager second factory Method and third one is Api Repository.
Factory Method:
Best practice method always use this method.
namespace QaisarSatti\Module\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_product;
public function __construct(
\Magento\Catalog\Model\ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
}
public function getLoadProduct()
{
$product_id=7;
return $this->_productloader->create()->load($product_id);
}
}
class Product extends \Magento\Framework\View\Element\Template
{
protected $_product;
public function __construct(
\Magento\Catalog\Model\ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
}
public function getLoadProduct()
{
$product_id=7;
return $this->_productloader->create()->load($product_id);
}
}
Api Repository:
This was introduce in Magento 2.1 by magento.
namespace QaisarSatti\Module\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
public function getProduct()
{
$productId=7;
return $product = $this->productRepository->getById($productId);
}
}
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
public function getProduct()
{
$productId=7;
return $product = $this->productRepository->getById($productId);
}
}
Object Manager:
No recommended method to use in magento2 but so magento use it so here it is just for knowledge.
$product_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);