Magento 2 – get product by sku
This post is about how to get product by sku in Magento 2. There are various different possibilities, I show you all you need to know about this.
Magento 2 – get product by sku
First of all, you need a model where you can inject needed models. A very common answer is to use a product repository model like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | private $productRepository; public function __construct( \Magento\Catalog\Api\ProductRepositoryInterface $productRepository ... ) { $this->productRepository = $productRepository; ... } public function getProductBySku($sku) { return $this->productRepository->get($sku); } |
For this you need to inject product repository interface to your model and call get() method with desired sku. This works, but my favorite method is to use a product factory object. This is also the preferred option in Magento 2 core, so it is always a good idea to use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private $productFactory; public function __construct( \Magento\Catalog\Model\ProductFactory $productFactory ... ){ $this->productFactory = $productFactory; ... } public function getProductBySku($sku) { $product = $this->productFactory->create(); return $product->loadByAttribute('sku', $sku); } |
The factory option uses lazy loading, so your product model has not all attributes set for use. If you need the full product model, you should change last two lines of code to:
1 2 | $product = $this->productFactory->create(); return $product->load($product->getIdBySku($sku)); |
Loading product by factory is the fastest method, so it is a good idea to use it to speed up you Magento 2 shop. I already showed you how to speed up Magento 2 product save.
Conclusion
As always there are many ways to get the expected result. To get product by sku you can use repository or factory objects. Factory objects should be used.
What is your favorite option?