Jigar KarangiyaJigar Karangiya

Conditions for Collections in Magento 2

JK
Jigar Karangiya
· 3 min read
Conditions for Collections in Magento 2

Collections in Magento 2 (Now Adobe Commerce), are among the most powerful tools for retrieving and manipulating data directly from the database. Whether you’re working with products, customers, or orders — knowing how to filter and refine your collection data efficiently is essential for any Magento 2 developer.

In this guide, you’ll learn everything about applying conditions to collections , including all condition types (eq, neq, like, in, nin, gt, lt, from-to, and more), along with real-world examples and best practices to help you write optimized, production-ready Magento 2 code.


Collections in Magento 2

In Magento 2, collections are the backbone of data retrieval.
They use two primary filtering methods depending on the entity type:

  • addFieldToFilter() → Used for flat tables (e.g., sales, customers)
  • addAttributeToFilter() → Used for EAV-based entities (e.g., products, categories)

Each method accepts a field name and a condition array that defines the filtering logic.


Basic Syntax

php
$collection->addFieldToFilter($field, $condition);

or for product/category (EAV) collections:

php
$collection->addAttributeToFilter($attribute, $condition);

Condition Types in Magento 2

Let’s break down all the commonly used condition operators with clear examples.

1. Equals (eq)

Filters records where the field equals the given value.

php
$productCollection->addAttributeToFilter('status', ['eq' => 1]);
$orderCollection->addFieldToFilter('state', ['eq' => 'complete']);

Shorthand:

php
$orderCollection->addFieldToFilter('state', 'complete');

Use case: Most common condition, when you need exact matches.

2. Not Equals (neq)

Filters records where the field does not equal the given value.

php
$productCollection->addAttributeToFilter('status', ['neq' => 0]);
$customerCollection->addFieldToFilter('group_id', ['neq' => 1]);

Use case: Exclude specific values (e.g., disabled, archived, or inactive data).

3. Like (like)

Performs SQL LIKE pattern matching.

php
$productCollection->addAttributeToFilter('sku', ['like' => '%ABC%']);
$customerCollection->addFieldToFilter('email', ['like' => '%gmail%']);

Use case: Searching text or patterns (e.g., partial SKU, email domain).
Use % as a wildcard:

  • %ABC% → contains
  • ABC% → starts with
  • %ABC → ends with

4. In (in)

Filters where the field value is in an array of values.

php
$productCollection->addAttributeToFilter('entity_id', ['in' => [1, 2, 3]]);
$orderCollection->addFieldToFilter('state', ['in' => ['processing', 'complete']]);

Use case: Match against multiple allowed values efficiently.

5. Not In (nin)

Filters where the field value is not in an array.

php
$productCollection->addAttributeToFilter('entity_id', ['nin' => [5, 10]]);
$orderCollection->addFieldToFilter('state', ['nin' => ['closed', 'canceled']]);

Use case: Exclude a list of specific values.

6. Greater Than (gt)

php
$productCollection->addAttributeToFilter('price', ['gt' => 100]);

Use case: Numeric or date comparisons where value > X.

7. Greater Than or Equal (gteq)

php
$orderCollection->addFieldToFilter('grand_total', ['gteq' => 500]);

Use case: Include values equal to the threshold as well.

8. Less Than (lt) & Less Than or Equal (lteq)

php
$productCollection->addAttributeToFilter('price', ['lt' => 50]);
$orderCollection->addFieldToFilter('grand_total', ['lteq' => 1000]);

Use case: Find data below or up to a certain limit.

9. Range: From–To (from, to)

php
$productCollection->addAttributeToFilter('price', ['from' => 50, 'to' => 100]);

Use case: Date ranges, numeric ranges, price filters.

10. Null / Not Null (null, notnull)

php
$productCollection->addAttributeToFilter('description', ['null' => true]);
$orderCollection->addFieldToFilter('customer_note', ['notnull' => true]);

Use case: Find records with or without specific data filled in.

Combining Multiple Conditions

AND Logic (Default)

php
$productCollection->addAttributeToFilter('status', 1);
$productCollection->addAttributeToFilter('price', ['gt' => 50]);

All conditions must be true.

OR Logic

php
$productCollection->addAttributeToFilter([
    ['attribute' => 'status', 'eq' => 1],
    ['attribute' => 'status', 'eq' => 2]
]);

At least one condition must match.


Complex AND/OR Combinations

php
$productCollection->addAttributeToFilter([
    [
        ['attribute' => 'status', 'eq' => 1],
        ['attribute' => 'price', 'gt' => 50]
    ],
    [
        ['attribute' => 'status', 'eq' => 2],
        ['attribute' => 'price', 'lt' => 100]
    ]
]);

Inner arrays = AND
Outer arrays = OR


Real-World Examples

Example 1: Active Products in Price Range

php
$collection->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('price', ['from' => 50, 'to' => 100])
    ->addAttributeToFilter('visibility', ['in' => [2, 4]]);

Example 2: Recent Orders by Customer Group

php
$dateFrom = date('Y-m-d H:i:s', strtotime('-30 days'));
 
$collection->addFieldToFilter('customer_group_id', ['in' => [2, 3, 4]])
    ->addFieldToFilter('created_at', ['gteq' => $dateFrom])
    ->addFieldToFilter('state', ['nin' => ['canceled', 'closed']])
    ->setOrder('created_at', 'DESC');

Example 3: Search Products by Name or SKU

php
$collection->addAttributeToFilter('status', 1)
    ->addAttributeToFilter([
        ['attribute' => 'name', 'like' => '%'.$searchTerm.'%'],
        ['attribute' => 'sku', 'like' => '%'.$searchTerm.'%']
    ]);

Example 4: Customers with Valid Email

php
$collection->addFieldToFilter('is_active', 1)
    ->addFieldToFilter('email', ['notnull' => true])
    ->addFieldToFilter('email', ['neq' => ''])
    ->addFieldToFilter('created_at', ['gteq' => '2024-01-01 00:00:00']);

Best Practices

Select only needed attributes:

php
$collection->addAttributeToSelect(['name', 'price']);

Limit results for performance:

php
$collection->setPageSize(20)->setCurPage(1);

Preferin over multiple ORs:

php
$collection->addFieldToFilter('status', ['in' => [1, 2, 3]]);

Filtering byentity_id, status, etc., is faster than unindexed text columns.

That’s it i think, will see you in the next upcoming blog.

You may also like,

How to Change Order Status Programmatically in Magento 2

How to Create a Helper Class in Magento 2?

Add Yes/No Attribute in Magento 2 programmatically

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts