Magento – Magento2 – product collection filter out of stock products

magento2product-collection

I could not find any relevant reference how to filter out products that are "Out of Stock" when dealing with product collection.
Here is the code sample:

<?php

$collection = $this->productCollectionFactory->create();
$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$collection = $this->_addProductAttributesAndPrices($collection);

return $collection;

I have set "Display Out of Stock Products" to "No" but that has no affect on given code sample. Is there a common way (e.g. helper method) that can be used to filter out of stock products based on config value set?

Best Answer

To bypass removing out of stock products in frontend (which could happens if you switched off showing out of stock items at stock options config page) we just need to set up a flag before we load the collection as

$collection->setFlag('has_stock_status_filter', true)

where $collection is instance of Magento\Catalog\Model\ResourceModel\Product\Collection