Back to Top

Update product stock programmatically in magento2

Updated 21 February 2024

Here we learn how to update product stock programmatically in magento2

Here we define function in helper file of module to update product stock and use this function where we want to update product stock.

namespace YourNameSpace\ModuleName\Helper;

use Magento\Framework\App\Filesystem\DirectoryList;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
    protected $_product;

     * @var Magento\CatalogInventory\Api\StockStateInterface 
    protected $_stockStateInterface;

     * @var Magento\CatalogInventory\Api\StockRegistryInterface 
    protected $_stockRegistry;

    * @param Magento\Framework\App\Helper\Context $context
    * @param Magento\Catalog\Model\Product $product
    * @param Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
    * @param Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Model\Product $product,
        \Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, 
    ) {
        $this->_product = $product;
        $this->_stockStateInterface = $stockStateInterface;
        $this->_stockRegistry = $stockRegistry;

     * For Update stock of product
     * @param int $productId which stock you want to update
     * @param array $stockData your updated data
     * @return void 
    public function updateProductStock($productId,$stockData) {
        $product=$this->_product->load($productId); //load product which you want to update stock
		$stockItem=$this->_stockRegistry->getStockItem($productId); // load stock of that product
		$stockItem->setData('is_in_stock',$stockData['is_in_stock']); //set updated data as your requirement
		$stockItem->setData('qty',$stockData['qty']); //set updated quantity 
		$stockItem->save(); //save stock of item

Thanks for reading the article 🙂 , I hope you liked it. Also, do check out Magento 2 Google Shopping Feed extension which allows you to showcase your Magento 2 online store’s products on Google using Shopping Feeds.

Searching for an experienced
Magento Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


  • Jeff
    • Neelesh Singh (Moderator)
  • Fabio Bozzo
  • Marc
  • Alex
  • Alex
  • Jacco Amersfoort
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home