Magento 2 get product collection by product SKU

0
254
Magento 2 get product collection by product SKU

In this article, you going to see how to get Magento 2 get product collection by product SKU programmatically in a detail and step by step.

If you are looking for this topic then you are at a right place.

Lets start with the topic Magento 2 get product collection by product SKU programmatically.

Use product SKU get product collection in Magento.

To fetch the product data using product SKU, use function called getProductBySKU() function.

The get Product By SKU function can be used by using interface as below.

\Magento\Catalog\Api\ProductRepositoryInterface $productRepository

Use the below code snippet to fetch the product collection using product SKU.

<?php
namespace VendorName\ModuleName\PathtoBlock;

class Product extends \Magento\Framework\View\Element\Template
{
/**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
    * Get Product by SKU
    * @param mixed
    * @return \Magento\Catalog\Model\Product $product
    */
    public function getProductBySKU($sku)
    {
        try {
            $product = $this->productRepository->get($sku);
        } catch (\Exception $exception) {
            throw new \Magento\Framework\Exception\NoSuchEntityException(__('Such product doesn\'t exist'));
        }
        return $product;
    }
}

Below is code snippet for calling a function using product SKU to get product collection data.

$sku = '32-TE31';
$product = $block->getProductBySKU($sku);
echo $product->getName(); // product name
echo $product->getId(); // product id

At the end, you will get product collection.

After adding the code for get product collection data, execute the below command to get out put.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f

Magento 2 get Order Items Collection by Item Id

Conclusion :

Finally, we have done with the topic of getting product collection completely.

With the help of the above code snippet, one can do the operation for Magento to get product collection data by SKU programmatically.

I hope you like this article and if you have any query, please comment below.