Ask your Question

Write to us

Ask Question

Magento2: How to get Product Details by SKU or Product Id

Sikha Goel

We can use below code in our controller file as well as in block file according to our need.

We are using the below code in our block file of our module.

Path: app/code/Letsknowit/HelloWorld/Block/Helloworld.php

<?php

 

namespace LetsknowitHelloWorldBlock;

class HelloWorld extends MagentoFrameworkViewElementTemplate

{    

    protected $_productRepository;

     

    public function __construct(

        MagentoCatalogModelProductRepository $productRepository,

        MagentoBackendAppActionContext $context

     )

     {

        $this->_productRepository = $productRepository;

        parent::__construct($context);

     }

    public function getProductDetailsById($productid)

      {

        return $this->_productRepository->getById($productid);

     }

  public function getProductDetailsBySku($productSku)

     {

        $productCollection = $this->_productRepository->get($productSku);

     }

 

}

 ?>

 

 

IN our phtml file we can call this function as below

 

<?php 

     $productSku = '123456ERT';

     $productDetails = $block->getProductDetailsBySku($productSku);

?>

Sikha Goel