Magento 2 product collection filter by attribute

Today we discuss how in Magento 2 product collection filters by attribute. We take the example of product collection and filter it by given size. So here is our example.

protected $_productCollectionFactory;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
         $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
        $productCollection = $this->_productCollectionFactory->create();
        $productCollection->addAttributeToFilter('size',  array('notnull' => true));

        return $productCollection;
     
     }

Note: You can sort any collection following this example.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!