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 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?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'); } } } |
1 2 3 4 5 6 7 |
protected $helper; public function __construct([Vendor]\[Module]\Helper\Data $data) { $this->helper = $data; } $this->helper->productExistBySku('AB1'); $this->helper->productExistById(123); |
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.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Where to add this construct function
Hello Pavani,
You can add the construct function in your custom class or where you want this functionality in the existing class.
Thank You