Magento – How to get product stock status on the listing page in Magento 2

inventorymagento2productstock-availabilitystock-status

I am using Magento 2.3.1

I want to display stock status on the listing page. So, how can I get "Stock Status" attribute value on the listing page?

I have tried below code:

<?php 
 $_productCollection = $block->getLoadedProductCollection();
 foreach ($_productCollection as $_product){

    $stock_status = $_product->getResource()->getAttribute('quantity_and_stock_status')->getFrontend()->getValue($_product);

 } 
?>

And tried below as well:

<?php 
     $_productCollection = $block->getLoadedProductCollection();
     foreach ($_productCollection as $_product){

        $default_stock_status = $_product->getData('quantity_and_stock_status');

     } 
?>

But for each scenario, I got "Out of stock" even though the product is in stock
here quantity_and_stock_status is the default "Stock Status" attribute.

enter image description here

Best Answer

You can try the following code

public function __construct(
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
) {
    $this->stockRegistry = $stockRegistry;
}
// you can pass $product object to the function
public function getStockStatus($product)
{
    return $this->stockRegistry->getStockItem($product->getId());
}

You can get all the stock details by

$stockItem = $this->stockRegistry->getStockItem($product->getId());
$stockData = $stockItem->getData();
$stockItem->getIsInStock();

Hope it helps.