In Magento 2 how can we get a collection of products with only products that are in stock. Please help
2 Answers
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.
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);
-
-
2
-
1