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:
<?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 } } }
That’s it. Easy peasy, isn’t it? You can also use Magento 2 API to get products by SKU by calling a GET request.
Do share the post with fellow developers via social media.
Thanks.