Magento – How to load product collection in Magento 2

magento2object-managerproduct-collection

How to load product collection in Magento 2 and what is the difference between Magento 1 and Magento 2 load product collection

Best Answer

The standard collections are actually very similar. There are other similar structures, but for products you can load them in and load them just like Magento 1. Just like in Magento 1, if you are using the collection via iteration you do not have to load it as it's done implicitly.

As always in Magento 2, you should be injecting classes via dependency injection in your class constructor. Plus, if you are going to create more than one instance you can add "Factory" after any class and you'll get a wrapping class that allows you to generate as many as you want.

Here is the use of both together:

/** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
protected $collectionFactory;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
) {
    $this->collectionFactory = $collectionFactory;
}

public function yourMethod()
{
    // Use factory to create a new product collection
    $productCollection = $this->collectionFactory->create();
    /** Apply filters here */
    $productCollection->addAttributeToSelect('*');
    // Don't have to do this
    // $productCollection->load();

    foreach ($productCollection as $product){
         echo 'Name  =  '.$product->getName().'<br>';
    }  
}

With thanks to @megi for the example usage code in their answer.

Related Topic