Magento 2 get product collection
Today we talk about Magento 2 get product collection. First we need to familiar with model collection structure of magento 2. Magento 2 use the collection class for get all record from database table. SO let start with coding. We are using the Factory method here.
protected $_productCollectionFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
) {
$this->_productCollectionFactory = $productFactory;
}
public function getProductCollection()
{
return $this->_productCollectionFactory->create()->addAttributeToSelect('*');
}
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
) {
$this->_productCollectionFactory = $productFactory;
}
public function getProductCollection()
{
return $this->_productCollectionFactory->create()->addAttributeToSelect('*');
}
To Fetch Data in phtml file
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
echo $product->getName().'<br />';
}
foreach ($productCollection as $product) {
echo $product->getName().'<br />';
}
3 thoughts on “Magento 2 get product collection”
Leave a Reply
You must be logged in to post a comment.
This is missing –> parent::__construct($context, $data);
Thanks for your feedback but it is not necessary for this tutorial. because the tutorial is general not specific to block or etc.
Is it possible to apply the current filter to complete website.