Site icon MageComp Blog

How to Update Product Stock Programmatically in Magento 2

How to Update Product Stock Programmatically in Magento 2

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.

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

Conclusion:

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!

Exit mobile version