Magento 2: Get Product By Sku and Id

This is the normal way to get Product, but not all the attributes are shown. It is better to use the third method where we convert our sku to Id and then get the full product.

Method one: Using the Repository Service Contract

I personally recommend using Interface as it is the Service Contract.

private $productRepository; 

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ...
) {
    $this->productRepository = $productRepository;
    ...
}

public function getProductBySku($sku)
{
    return $this->productRepository->get($sku);
}

 

Method 2: Using Factory

This method is recommended by Magento to prevent tightly coupled code. You have to use this if you want to create new entity.

private $productFactory;

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

public function getProductBySku($sku)
{
    $product = $this->productFactory->create();
    return $product->loadByAttribute('sku', $sku);
}

Load By ID

public function getLoadProduct($id)
    {
        return $this->_productFactory->create()->load($id);
    }

 

Method 3: Using Factory but get the full product information

$product = $this->productFactory->create();
return $product->load($product->getIdBySku($sku));

 

Leave a Reply

Your email address will not be published. Required fields are marked *