1

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

2 Answers 2

7

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.

0
1

Try using addInStockFilterToCollection available in the CatalogInventory module to add an InStock Filter to the collection. See example below.

$productCollection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
3
  • How will we do the same in magento 2?
    – chin
    Jan 3, 2017 at 6:19
  • 2
    @chin , For Magento2 see Shahab's answer below
    – Irfan Khan
    Jan 3, 2017 at 6:23
  • 1
    Question is for magento 2 not 1.x Jan 3, 2017 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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