Magento 2 get product by id
In Magento 2 there are more than one method to get product by id. For Magento programmers, this is one of the most often used methods. Products are needed in own modules, scripts or in many phtml files. I show you how to get products by various different methods.
Magento 2 get product by id
The suggested way to get products (or other models) in Magento 2 is by factory. Factories are a new design pattern that has been implemented in the new version of you shop software. But there are also other option that may not be as fast and have other problems…
By factory
We can get a product by the following code:
1 2 3 4 5 6 7 8 9 10 | protected $_productFactory; ... public function __construct( ... \Magento\Catalog\Model\ProductFactory $productFactory ) { ... $this->_productFactory = $productFactory; ... } |
Somewhere else in your model you get a product by id:
1 | $product = $this->_productloader->create()->load($id); |
By object
The second and the known Magento 1 option is to get a product model by an object. In Magento 2 you need a object manager instance. The object manager is a singleton class, so you can get it from everywhere. It is a good idea to save this instance in your __construct method to minimize lines of codes but not necessary.
1 2 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id); |
By repository
Repositories are another design pattern that was implemented into Magento 2. The repository design pattern can also be used to get objects, for example product objects:
1 2 3 4 5 6 7 8 9 10 | protected $_productRepository; ... public function __construct( ... \Magento\Catalog\Api\ProductRepositoryInterface $productRepository ) { ... $this->_productRepository = $productRepository; ... } |
You will then get to product for example by sku:
1 | $product = $this->_productRepository->get($sku); |
You can also get a product by id. This works as follows:
1 | $product = $this->_productRepository->getById($id); |
Conclusion
Magento 2 offers you a wide range of possibilities to get product by id.