How to load product collection in Magento 2 and what is the difference between Magento 1 and Magento 2 load product collection
-
Check this stackoverflow.com/a/35679085/1728526– amitshreeCommented Jun 19, 2017 at 13:32
-
You can check this tested version to make sure it work well here magento2x.com/…– PhucCommented Jul 18, 2018 at 6:48
-
I'm created Magento 2 tutorials channel please Like and Support youtube.com/channel/UC2JghzAPB7wNBDY0u-OtAig/videos– Sonu MadeshiyaCommented Oct 7, 2022 at 5:57
10 Answers
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.
<?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>';
}
?>
-
5It is not recommended to use the objectManager directly, try to use factorys instead as Robert Egginton suggested.– TrytoFlyCommented Oct 12, 2017 at 10:18
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.
-
Also consider using an Iterator when working with large collections and avoid memory_limit errors. magento.stackexchange.com/a/213059/555 Commented Aug 23, 2018 at 1:02
=> 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;
}
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);
}
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();
}
-
Hello, Is it possible to apply this new product collection throughout the website ? 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
-
-
@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
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()); }
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();
- 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;
}
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
}
?>
-
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