8

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

3

10 Answers 10

17

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.

9
 <?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$collection = $productCollection->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
}  
?>
1
  • 5
    It is not recommended to use the objectManager directly, try to use factorys instead as Robert Egginton suggested.
    – TrytoFly
    Commented Oct 12, 2017 at 10:18
7

Here is the best way to get product collection in magento

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

public function getCollection()
{
    $collection = $this->product->create()->getCollection();
    return $collection;
}

public function loadProduct($id)
{
    $product = $this->product->create()->load($id);
    return $product;
}

In the magento 1 you can get collection using below code

$productCollection = Mage::getModel('catalog/product')->getCollection();

here we call Model catalog/product and then getCollection() method to get all product collection

In Magento 2 First we need to call class of product collection Magento\Catalog\Model\Product

then we need to call method create(); Magento 2's create method is same as Magento 1's getModel then we call collection.

1
3

=> Magento 1 :

$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $prod) {
$product = Mage::getModel('catalog/product')->load($prod->getId());
}

=> Magento 2 :

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

 public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(3); // fetching only 3 products
    return $collection;
}
1
  • how to get new product collection only? Commented Feb 8, 2019 at 11:21
2

The best way to load the product collection using repositories in Magento 2 service contracts.

Inject the interface Magento\Catalog\Api\ProductRepositoryInterface in your constructor as follows

protected $productRepo; 

public function __construct(    
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepo
) {
    $this->productRepo = $productRepo;
}

public function getProductById($itemId)
{
    return $this->productRepo->getById($itemId);
}

public function getProductBySku($sku)
{
    return $this->productRepo->get($sku);
}
1

Magento 2 getting the product is totally different from Magento 1. in Magento 1 we use this code to get the collection.

$productCollection = Mage::getModel('catalog/product')->getCollection();

To get product collection in Magento 2 use following code.

 protected $_productCollectionFactory;

 public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    { 
      return   $this->_productCollectionFactory->create(); 

     }

Reference

8
  • Hello, Is it possible to apply this new product collection throughout the website ?
    – inrsaurabh
    Commented Jun 17, 2018 at 17:30
  • how to filter with most order items, i used below code, its not working, ->setOrder('ordered_qty', 'desc'); Commented Jan 11, 2019 at 8:37
  • @jafarpinjar use order item collections Commented Jan 11, 2019 at 8:44
  • @QaisarSatti, i am getting product collection with category filter, how to use with this? Commented Jan 11, 2019 at 8:49
  • @jafarpinjar that is not related to this answer. create new question for that Commented Jan 11, 2019 at 8:53
1

Please follow the steps to load product collection: Step 1. Create your own block file

app/Code/Vendor/ModuleName/Block/ClassName.php

Copy Paste following code into your block file. protected $productCollectionFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

public function getProductCollection()
{
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(5); // Fetch Only 5 Products
    return $collection;
}

}

Step 2: Display product collection in phtml file

$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { print_r($product->getData()); }

0

Try this one it's working for me.

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

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

$collection = $productCollection->create()

 ->addAttributeToSelect('*')

 ->addAttributeToFilter('status', '1')

 ->load();
0

  1. List item
public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

 public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    return $collection;
}
0

You can load product collection From Helper also, so that You can use that collection anywhere.like thise...

<?php

namespace Vendor\Module\Helper;

use \Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
 {
protected $_productCollectionFactory;

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;

    parent::__construct($context);
}

**/* Get full Products Collection*/**
public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(6);
    return $collection;
}

}

Now if you want to call it in any phtml file you can achieve it easily like these.

<?php 
$helper = $this->helper('Vendor\Module\Helper\Data');
$collection = $helper->getProductCollection();

foreach ($collection as $product) {
                 $result = [
                    'id'        => $product->getId(),
                    '_sku'      => $product->getSku(),
                    'product_url' => $product->getProductUrl($product),
                    'title'     => $product->getName(),
                    'raw_price' => $product->getPrice()
                ];
?>
<span class="price">
<?= $result['raw_price'] ?>
</span>
<?php
}
?>
1
  • even if this works, using helpers is not a good practice. Also, putting methods into a helper so you can use them everywhere in templates is even worse.
    – Marius
    Commented Feb 3, 2020 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.