Magento – Magento 2: Change Product status OUT OF STOCK Programmatically

magento2out-of-stockproductstock

I need to change product as out of stock without changing its Quantity. I mean if a product having quantity 5, It will be same but product would be changed to OUT OF STOCK. Is it possible in magento?

Best Answer

Try with this

public function __construct(
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
    \Magento\Catalog\Model\Product $product,
) {
    $this->_stockRegistry = $stockRegistry;
    $this->_product = $product;
}

And after

$product=$this->_product->load($productId); //load product which you want to update stock
$stockItem=$this->_stockRegistry->getStockItem($item['product_id']); // load stock of that product
$stockItem->setData('is_in_stock',0);       
$stockItem->save();
$product->save();
Related Topic