6

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

  • 1
    Did you find any solution? I am having the same problem. – Sarvagya Jan 23 '18 at 12:00
1

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();
    }
}
-1

Use below code to filter "Out of Stock" product:

$productCollection =
$objectManager->create('Magento\Catalog\Model\Product\LinkFactory');
$productCollection->create()->getProductCollection()->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' =>
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED));
$productCollection->joinField( 'qty', 'cataloginventory_stock_item',
'product_id=entity_id', '{{table}}.stock_id=1');

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.