6

I have to setup Product 'in stock' and update Quantity programmatically. Here is my code I am trying:

$product->setData('is_in_stock', 1);
$product->setData('qty', 5);
$product->save();
17

Can you please try below code? It will save inventory data.

$product->setStockData(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->setQuantityAndStockStatus(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->save();
4
  • Thanks SH Patel, I used last three line of above code and it works for me. May 3 '17 at 6:08
  • I used only first and third line but it not worked. the second line is also important to get it work. Nov 7 '17 at 14:45
  • I used second line and third line and it is working, so first line $product->setStockData(['qty' => $stockData, 'is_in_stock' => $stockData]) is unnecessary. @shashank
    – Key Shang
    Jun 19 '18 at 4:18
  • This code working for me bit only for enable product quantity update. Which products are disable, it's quantity not update. Can you help me for solve it.
    – Anil
    Jun 27 '19 at 11:02
1

In Magento 2.3 was deprecated change stock directly via setStockData(...) Instead of it, you MUST use this way for updating product stock

  1. Init product stock repository
    public function __construct(
        \Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
    ) {
        $this->productStockRepository = $productStockRepository;
    }

  1. Use Repository for product stock update
    $productStock = $productStockRepository->get($entity->getId());
    $productStock->setStockData(['is_in_stock' => false]);
    $productStockRepository->save($productStock);

In case if you don't use Multi Source Inventory (Magento_InventoryApi extesions), you can update product stock this way:

  1. Init product stock registry
    public function __construct(
        \Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
    ) {
        $this->productStockRepository = $productStockRepository;
    }
  1. Get product stock item and change product stock
    $productStock = $productStockRegistry->getStockItem($entity->getId());
    $productStock = $productStockRepository->get($entity->getId());
    $productStock->setIsInStock(true);
    $productStock->setQty(10);
    $productStock->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.