Even though Magento 2 is a very flexible and easy-to-manage eCommerce platform, operating an online store may be rather challenging sometimes. Same as getting order data by increment ID, getting products by ID is certainly a crucial skill.
Since it is one of the most frequent operation ones comes across when working with Magento, you have to know how to do it. There are a few ways to do so, and in this article, you'll learn how to use each of them.
Post Contents [hide]
Get Product by ID Using Factory Method
The most common way to get a product by ID in Magento 2 is to use the factory method. To do that, use the following code:
protected $_productFactory;
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory
) {
$this->_productFactory = $productFactory;
}
After that, get the product by ID, by executing the below command.
$product = $this->_productFactory->create()->load($id);
Get Product by ID Using API Repository
API repository is the other method you can choose. Execute the following code to get product objects:
protected $_productRepository;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
Then run the command below to get the product by ID:
$product = $this->_productRepository->getById($id);
Get Product by ID Using Object Manager
Finally, object manager makes it possible to get the product by ID in Magento as well. As you probably know, this method is rather complicated. Yet, the following code will help you to get products by ID:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
Note: we recommend you avoid the direct usage of the object manager method since it hides the real dependencies of the class.
There you go. Each of the methods is meant to optimize development work for you. Just select the one that meets your requirements the best.
Once you master getting the product by ID, you can go on and learn how to get product collection by category ID in Magento. it might come in handy.