Hello Magento Friends,
In this Magento Tutorial, I will illustrate How to Update Product Stock Programmatically in Magento 2.
Product stock is a very important thing that the admin needs to manage to avoid out-of-stock situations. Admin can Setup Product Stock in Magento 2 to manage store inventory. Once the product stock is configured, the stock information is updated when the products are sold out. Admin can Get Product Stock Information in Magento 2 easily for smooth management of inventory.
Magento 2 store admin can update the product stock programmatically. Let’s check out the steps for the same.
Step 1: We need to create a “Data.php” file inside our extension at the following path
app\code\Vendor\Extension\Helper\
Now add the code as follows
<?php namespace Vendor\Extension\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { protected $_productobj; protected $_stockRegistry; public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Catalog\Model\Product $productobj, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, ) { $this->_productobj = $productobj; $this->_stockRegistry = $stockRegistry; parent::__construct($context); } public function updateProductStock($productId,$stockData) { $product=$this->_productobj->load($productId); $stockItem=$this->_stockRegistry->getStockItem($productId); $stockItem->setData('is_in_stock',$stockData['is_in_stock']); $stockItem->setData('qty',$stockData['qty']); $stockItem->setData('manage_stock',$stockData['manage_stock']); $stockItem->setData('use_config_notify_stock_qty',1); $stockItem->save(); $product->save(); } }
Step 2: Define the helper class and use it per your requirement. You need to pass product id as a first argument and stock data in an array as a second argument. Following is the example of a stock data array.
$stockData = array('is_in_stock'=>1,'qty'=> 5, 'manage_stock'=> 1);
That’s it! Using the above method, you can easily Update Product Stock Programmatically in Magento 2. Admin can easily manage out-of-stock products by getting Out of Stock Products List and notifying customers when the product is back in stock through the Out of Stock Notification Module. To not disturb the customer shopping experience, the admin can even shift Out of Stock Products at Last in the product grid.
Happy Coding!
In modern web development, seamless navigation and state management are crucial for delivering a smooth…
Magento Open Source 2.4.8 beta version released on October 8, 2024. The latest release of…
Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…
As the world of eCommerce continues to thrive, Shopify has become one of the most…
Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…
Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…