Get Product Collection with a Specific Attributes in Magento 2

In this article we'll discuss how to get product collection with a specific attribute in magento 2. We'll get collection in a block file.

Check the following code to get specific attribute collection.

Copy
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();
        $collection->addAttributeToSelect('name');
        $collection->addAttributeToSelect('price');
        return $collection;
    }
}

In above code I have add name and price attribute. So, we'll get that with collection. But, incase if you want to get all attribute with collection then replace below code with above.

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

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.

Copy
$productCollection = $block->getProductCollection();
foreach ($productCollection 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 post 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 note with your team.

Review other articles maybe it'll help you too.