How To Check If Product With SKU Exists in Magento 2?

How embarrassing it would be for a Magento 2 developer to develop a complete functionality based on the product ID and try to implement it only to realize in the end that it won’t work as the product only does not exist in the first place!!

Happens!

The easy escape to such a situation is to check if the product with SKU exists in Magento 2! Prior to using the SKU anywhere, you need to check if that product exists in Magento 2 store or not.

If the answer is yes, then only you can use the product SKU for further conditions.

And the programmatic method to do so is as below:

Method to Check If Product With SKU Exists in Magento 2:

<?php
namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductRepository;

class Data extends AbstractHelper
{
    protected $product;
    protected $productRepository;
	
    public function __construct(
        Context $context,
        Product $product,
		ProductRepository $productRepository
    )
    {
	    $this->product = $product;
		$this->productRepository = $productRepository;
        parent::__construct($context);
    }

    public function productExistBySku($sku)
    {
		if($this->product->getIdBySku($sku)) {
			$this->_logger->info('Product Exist'); 
		}
    }
	
	public function productExistById($productId)
    {
		if($this->productRepository->getById($productId)) {
			$this->_logger->info('Product Exist');   
		}
    }
}

Than simply crate Helper class object and call above function like :

protected $helper;

public function __construct([Vendor]\[Module]\Helper\Data $data) 
{
   $this->helper = $data;
}

$this->helper->productExistBySku('AB1');
$this->helper->productExistById(123);

That’s it.

Check if product with SKU exists in Magento 2 with the above code easily.

Any doubts?

Mention them in the Comments section below.

I’d be happy to help.

Don’t forget to share this trick with fellow developers via social media to save them from going through unnecessary development and work smart!

Thanks.