Magento – Magento 2 How to get product collection of all products

catalogmagento2.2product-collection

I am trying to fetch the product collection in Magento 2 which return the all products including

-> with all instock and out of stock products

-> with all Visibility (Not Visible Individually,Catalog,Search,Catalog, Search)

-> with all status (Enabled,Disabled)

Is it possible to get this type of product collection?

Best Answer

Using bellow code, you fetch the product which is currently enable.

<?php
namespace Vendor\Extension\Block;

class Yourblock extends \Magento\Framework\View\Element\Template
{   
    /*Product collection variable*/ 
    protected $_productCollection;

    protected $stockFilter;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection,
        \Magento\CatalogInventory\Helper\Stock $stockFilter,        
        array $data = []
    )
    {    
        $this->_productCollection= $productCollection;
        $this->stockFilter = $stockFilter;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {

        $collection = $this->_productCollection->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

        // ADD THIS CODE IF YOU WANT IN-STOCK-PRODUCT
        $this->stockFilter->addInStockFilterToCollection($collection);

        return $collection;
    }
}
?>

NOTE You need to change getProductCollection() function code for your other requirement.

Related Topic