How to Get All Products (In Stock, Out of Stock, Enabled, Disabled) in Magento 2

magento2product-collectionstock

I've been trying to figure this out for too many hours now…

How can I fetch every products from the database?

I've tried a lot of different method of getting the products, but all of them either don't work at all or only return products in stock.

This is what I'm using at the moment and it returns every products in stock (5 products out of the ~50 products that I can see in the admin):

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->load();

foreach ($collection->getItems() as $productItem) {
    $product = $productItem->getData();
    echo $product['name'].'<br>';
}

If it matters, my goal is to update these products (name, description, stock, price…).

Best Answer

You can apply status and visibility filter in collection to fetch all Products:

/**
 * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
 * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
 * @param \Magento\Catalog\Model\Product\Visibility $productVisibility
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
    \Magento\Catalog\Model\Product\Visibility $productVisibility
) {
    $this->productCollectionFactory = $productCollectionFactory;
    $this->productStatus = $productStatus;
    $this->productVisibility = $productVisibility;
}

/**
 * @return \Magento\Framework\DataObject[]
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function getProducts()
{
    /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
    $collection = $this->productCollectionFactory->create();
    $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
    $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
    $collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
        ->addAttributeToFilter('visibility', ['in' => $this->productVisibility->getVisibleInSiteIds()]);

    return $collection->getItems();
}

You can check more on below links:

How to get a list of all products in Magento 2?

How to get only out of stock products in magento 2