How to Get Product Collection in Magento 2

In this article we'll discuss how to get product collection in magento 2 in 2 different ways. First we'll get product collection using a factory method in a block file and in a second method we'll get product collection using ObjectManager but I'll recommended you to use Dependency Injection rather than directly using ObjectManager.

Let's get started!!

Use following code to get product collection in block file.

saveCopyzoom_out_map
namespace Devhooks\Module\Block; class Module extends \Magento\Framework\View\Element\Template { protected $productFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory, array $data = [] ) { $this->productFactory = $productFactory; parent::__construct($context, $data); } public function getProductCollection() { $collection = $this->productFactory->create(); return $collection; } }

In above code we use factory option and factory option uses lazy loading, so your product model didn't provide all attributes. If you need the full product data, then you need to load particular product collection see below code for more detail.

saveCopyzoom_out_map
$collection = $this->productFactory->create(); return $collection->load($product->getIdBySku($sku));

Now, we'll print the product collection in .phtml file. Check following code to get product collection in phtml file. In this code we just call getProductCollection method from our block.

saveCopyzoom_out_map
$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { echo "<pre>"; print_r($product->getData()); echo "</pre>"; }

You can also get the product collection using objectManager but it's not recommended way.

saveCopyzoom_out_map
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $collection = $productCollection->create() ->addAttributeToSelect('*') ->load(); foreach ($collection as $product){ echo "<pre>"; print_r($product->getData()); echo "</pre>"; }

Finally, we are done, let's flush or refresh cache and test the result.

That’s it.

I hope this article helped you to find what you were looking for. Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this article with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off