1

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

5

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.

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);
  • How will we do the same in magento 2? – chin Jan 3 '17 at 6:19
  • 2
    @chin , For Magento2 see Shahab's answer below – Irfan Khan Jan 3 '17 at 6:23
  • Question is for magento 2 not 1.x – Ronak Chauhan Jan 3 '17 at 7:00

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.