Getting product data is a need of many developers so this blog is the best for it. In this blog, we will explain how to get product data using SKU in Magento 2.
If you want to get product data by ID. Please Click Here
Factory method and object manager are the two different ways to lode Product data.
If you want to overuse this function, you can create it in Helper. Otherwise use the blog. We are currently using Helper.
- Load Product By SKU Using Factory Method :
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 VendorName\ModuleName\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 getProductDataUsingSku ($sku) { if ($this->productRepository->get($sku)) { $product = $this->productRepository->get($sku); $id = $product->getEntityId(); $name = $product->getName(); //$product->getData(); -> use this and get all product data } } } |
- Call phtml file :
1 2 3 4 |
$sku = “ACY–123”; $product = $block->getProductDataUsingSku($sku); echo $product->getName(); //$product->getData(); -> use this and get all product data |
- Load Product By SKU Using ObjectManager :
1 2 3 |
$sku = “A–123”; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get(‘Magento\Catalog\Api\ProductRepositoryInterface’)->get($sku); |
We’re sure you understand this blog and if there’s a problem show it in the comments section below.
Thank You!!..
We are bringing in the next block HOW TO GET PRODUCT COLLECTION USING A FACTORY METHOD IN MAGENTO 2