Magento 2 Products – How to Update Product Qty and Stock Status Programmatically

magento2productsprogrammaticallyqtystock-status

I want to update product qty and change Stock Status as in stock by programmatically by product id. I dont want to insert new product, but I want only update existing product by its id. Any one know how to do it ? I tried following code but not getting result.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();  
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
//$productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface');
//echo 'VERSION ==> '.$productMetadata->getVersion();

$product_id = 1;
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');


//$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$product->setQty(100);
$product->save();

Edit : i want to run in a root directory and simple one php file. I want to run as

localhost/m229/updateproduct.php

Best Answer

You can use below sample code

$product->setStockData(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->setQuantityAndStockStatus(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->save();