Magento – Magento 2 Filter product collection by only stock in products

collection;magento2productproduct-collection

In Magento 2 how can we get a collection of products with only products that are in stock. Please help

Best Answer

Magento 1

This snippet provides a collection of in-stock products, or products which do not have stock management enabled on them.

$productCollection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);

Magento 2

Use below code to your class to filter out of stock product:

protected $_stockFilter;

 public function __construct(
      ....
      \Magento\CatalogInventory\Helper\Stock $stockFilter
      ....
      ) 

      {
        $this->_stockFilter = $stockFilter; 
      }

in your method add the following code to add products that are in stock

public function getProducts() {

..........

 $this->_stockFilter->addInStockFilterToCollection($collection);

..........

}

Hope it helps.