Magento – Magento 2 get out of stock products in collection

collection;magento2out-of-stockproduct

I am trying to get all the products from the collection(both in stock and out of stock) but with no luck at all. The setting on admin needs to hide the out of stock products from frontend but I want to show them in a specific page.

This is my code:

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollection->addAttributeToSelect('*');
$productCollection->load();

This brings the in stock products only. How can I modify it to bring and the out of stock as well?

Thanks

Best Answer

If it helps anyone, this is the only way I've managed to get all products, including out of stock products, in a loop for updating the stock values.

I needed to use ->getAllIds() to get an array of all of the products IDs, and then load each product individually rather than loop through the whole collection.

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollectionIds = $productCollection->create()->getAllIds();

foreach ($productCollectionIds as $productId) {
    try {
        $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
        // do actions with product
    } catch (Exception $e) {
        $e->getMessage();
    }
}