Announcement

Collapse
No announcement yet.

How to Load Product by SKU in Magento 2? Complete Tutorial

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to Load Product by SKU in Magento 2? Complete Tutorial

    Thee are two different methods to get the product by SKU.
    1- Object Manager

    This is a simple and short method to get product by SKU but it is not recommended method by Magento.
    Code:
    $sku = “ABC”;
    $objectManager = \Magento\Framework\App\ObjectManager :: getInstance();
    $product = $objectManager -> get(‘Magento\Catalog\Model\Product’) -> loadByAttribute(‘sku’,$sku);
    2- Factory Method
    This is a proper method recommended by Magento.
    Code:
    <?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 Code
    Code:
    $product = $this - > getLoadProduct(“ABC”);
    Echo $product -> getName();
    Complete Tutorial - magento 2 load products by SKU
Working...
X