I want to filter a collection of products by product (brand) attribute, thanks


you want to use product CollectionFactory

namespace Vendor\Yourmodule\Block;
class ProductCollection extends \Magento\Framework\View\Element\Template
    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->addAttributeToFilter('brand_id', array('eq' => 'brand_value'));

        return $collection;

Load product collection with specific attribute

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('brand', array('eq' => "brandcode"));    
foreach ($collection as $product) {

You can add filter like this..

protected $_product;

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

public function execute()
    $productCollection = $this->_product->getCollection()->addAttributeToFilter('brand', array('eq' => 'test'));
  • You can change your condition in array here I've added condition for Brand = Test. You can put neq instead of eq so then that will work like Brand != Test. Hope this will helphul to you!

Try this:

/** @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->addAttributeToFilter('brand', 'value_here')

    foreach ($productCollection as $product){
         echo 'Name  =  '.$product->getName().'<br>';

Hope you help this ;)

  • Shafeel Sha, thanks for answer, I want to get it in my custom module, what class do I need to inject for _pct? for \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory it doesn't work – Robinio Oct 18 '19 at 9:53
  • check updated answer – Shafeel Sha Oct 18 '19 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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