How to Update Product Stock Programmatically in Magento 2

 Steps to Update Product Stock Programmatically in Magento 2:

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);

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Set and Get Cookie in Magento 2