Magento 2How To GuideNovember 20, 2019

How to Load Product by SKU in Magento 2?

How to Load Product by SKU in Magento 2?

Loading products by SKU & ID in Magento 2 are the most sought-after queries. The purpose is to get the product’s details to perform various operations. We have already written a tutorial on how to load product by ID in Magento 2. Here, we will see how to load product by SKU. The same idea with a different approach.

Today, we'll show you two different ways to load product by sku in Magento 2:

  1. Object Manager
  2. Factory Method

Load Product by SKU using Object Manager

This is a short method to get product by SKU and it’s not recommended by Magento.
	
$sku="ABC";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);

Laod Product by SKU using Factory Method

This is a proper method recommended by Magento to load product by SKU.
<?php 
namespace FME\Module\Block; 

class Product extends \Magento\Framework\View\Element\Template
 {
  protected $_productloader; 

  public function __construct( 
         \Magento\Catalog\Model\ProductFactory $_productloader 
         ) { 
         $this->_productloader = $_productloader;

           }
public function getLoadProduct($sku)
    {
        return $this->_productloader->create()->loadByAttribute('sku', $sku);
    }
}

phtml file code

$product=$this->getLoadProduct(“ABC”);
echo $product->getName();

Conclusion:

In programming, there are often different ways to get a particular result. You can get product by SKU either by Object Manager or Factory Objects. The factory method is faster and hence recommended.

If you're having issues in loading product by SKU in Magento 2, then contact our support team to get an instant solution.

Check our tutorial to Get Product Collection by Category ID in Magento 2.

    This article was about:
  • Get product by sku
  • Load product by sku
  • Load product by sku in phtml
  • Magento 2.3 load product by sku
  • Load product by sku in Magento 2.4