How to check product is in stock status programmatically Magento 2?

While developing on Magento 2 dependent on the Product stock status, In stock or Out of stock, you need to check it programmatically using StockRegistryInterface.

Use the Magento\CatalogInventory\Api\StockRegistryInterface class to fetch product stock status.

Let’s take a simple example by passing the Product id, to check the Product stock status,

<?php
namespace Jesadiya\StockStatus\Model;

use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\CatalogInventory\Api\Data\StockItemInterface;

class Data
{
    /**
     * @var StockRegistryInterface|null
     */
    private $stockRegistry;

    public function __construct(
        StockRegistryInterface $stockRegistry
    ) {
        $this->stockRegistry = $stockRegistry;
    }

    /**
     * get stock status
     *
     * @param int $productId
     * @return bool 
     */
    public function getStockStatus($productId)
    {
        /** @var StockItemInterface $stockItem */
        $stockItem = $this->stockRegistry->getStockItem($productId);
        $isInStock = $stockItem ? $stockItem->getIsInStock() : false;
        return $isInStock;
    }
}

Call method with a required parameter,

$productId = 1;
echo $result = $this->getStockStatus($productId);

A result will be true if the product qty greater than 0 or Stock Status is set to In stock from the admin panel.

With the above code, snippet check the product stock status easily.

In this way Check the Product stock status programmatically in your Block or Model file.