Site icon MageComp Blog

How To Check If Product With SKU Exists In Magento 2

Hello, Magento Buddies!

Are you facing the same challenge as many developers today? Developing an entire functionality of a product using its ID only to find at the end that the product has gone to meet the maker? The product is no more in your store?

But, as the saying goes, every problem comes with a solution too! And so, here I am today with a solution for all of you facing the aforementioned problem. It is imperative to recheck once if the product exists or not in your Magento 2 store before using the SKU for any purpose elsewhere. 

Programmatic Way To Check If Product With SKU Exists In Magento 2

Step 1: Create a file named Data.php in the below-given path.

app\code\Vendor\Extension\Helper\

Now, add the below code in the file.

<?php

namespace Vendor\Extension\Helper;

use Magento\Framework\App\Helper\Context;

use Magento\Catalog\Model\Product;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper

{

    protected $product;

    public function __construct(Context $context,Product $product)

    {

        $this->product = $product;

        parent::__construct($context);

    }

    public function Checkproductexist($product_sku)

    {

        if ($this->product->getIdBySku($product_sku))

      $this->_logger->info('Product is Exist');

        else

  $this->_logger->info('Product is not Exist');

    }

}

Step 2: Next, add the below-given code in module phtml file:

<?php

$helper = $this->helper('Vendor\Extension\Helper\Data');

$product_sku = "product_sku"; // add your sku here

$helper->Checkproductexist($product_sku);

?>

After you have added the above code, check whether the product exists or not in the system.log (var/log/system.log) file.

Summing It Up!

That was one quick solution. Add this code properly and you will surely get the desired results. Also, it is quite important as checking whether the product exists or not is crucial before using its SKU anywhere.

To get your Magento store custom-developed, Hire a Dedicated Magento Developer and we will create your store just as you require it to be! Also, share this solution with your Magento friends. Catch you later. Till then, have a G’day! 

Happy Coding!

Exit mobile version