How To Load Products by SKU in Magento 2
Earlier, I posted a solution to get product collection by category ID in Magento 2.
The idea was to get the product information in Magento 2.
With a similar idea, but a different approach, I’ve come up with a solution to get product information by SKU in Magento 2 store.
You can load products by SKU in Magento 2 and then use the details for either developing an SKU based feature or fulfill crazy client requirements!
Method To Load Products by SKU in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php namespace Vendor\Module\Helper; use Magento\Framework\App\Helper\Context; use Magento\Catalog\Model\ProductRepository; class Data extends AbstractHelper { protected $productRepository; public function __construct(Context $context, ProductRepository $productRepository) { $this->productRepository = $productRepository; parent::__construct($context); } public function getProductData($sku) { if ($this->productRepository->get($sku)) { $product = $this->productRepository->get($sku); $id = $product->getEntityId(); $name = $product->getName(); print_r($product->getData()); // for all data } } } |
However, I am always ready to attend any doubts about the topic mentioned in the Comments section below.
Do share the post with fellow developers via social media.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hi Sanjay,
What is the difference between the ProductRepository and using MagentoCatalogModelResourceModelProductCollectionFactory?
Thanks
Hello,
Factory:
Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.
Repository:
A repository object is responsible for reading and writing your object information to an object store
You can also refer to https://magento.stackexchange.com/questions/158081/when-should-we-use-a-repository-and-factory-in-magento-2 for the details.
Thanks