PHPackages                             tijanidevit/query-filter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. tijanidevit/query-filter

ActivePackage[Database &amp; ORM](/categories/database)

tijanidevit/query-filter
========================

A simple, expressive, and powerful Laravel package that provides dynamic Eloquent models filters with clean syntax. It helps build reusable, maintainable, and readable query logic in Laravel apps.

1.0.0(5mo ago)320MITPHP

Since May 5Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/tijanidevit/laravel-query-filter)[ Packagist](https://packagist.org/packages/tijanidevit/query-filter)[ RSS](/packages/tijanidevit-query-filter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (1)Versions (10)Used By (0)

Query Filter for Laravel
========================

[](#query-filter-for-laravel)

A simple, expressive, and powerful Laravel package that provides dynamic Eloquent model filters with clean syntax. It helps you build reusable, maintainable, and readable query logic in Laravel applications.

[![Latest Version on Packagist](https://camo.githubusercontent.com/1be89a25cd237dd5720dad829f45edca52bcbe46e8ba459044323a311e294760/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74696a616e6964657669742f71756572792d66696c7465722e737667)](https://packagist.org/packages/tijanidevit/query-filter)[![Downloads](https://camo.githubusercontent.com/00d1e81537cf942fb75956659192fb9da19324f8d4e8befb07d6628223892578/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74696a616e6964657669742f71756572792d66696c7465722e737667)](https://packagist.org/packages/tijanidevit/query-filter)[![License](https://camo.githubusercontent.com/dd4bb05e2be36580d27d2429154db75183f4d704fa3ea735ade96f223e310835/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f74696a616e6964657669742f71756572792d66696c7465722e737667)](LICENSE)

---

Why Use This Package?
---------------------

[](#why-use-this-package)

In many Laravel applications, especially admin dashboards, reporting systems, and search filters, developers often repeat the same filtering logic:

```
$query = User::query();

if (request()->filled('name')) {
    $query->where('name', request('name'));
}

if (request()->filled('status')) {
    $query->where('status', request('status'));
}

return $query->get();
```

**With Query Filter, you can simplify this:**

```
User::query()
    ->filterBy([
        'name' => request('name'),
        'status' => request('status'),
    ])
    ->get();
```

---

Installation
------------

[](#installation)

Run the composer command:

```
composer require tijanidevit/query-filter
```

The package supports auto-discovery. If you are using Laravel &lt; 5.5, add the provider manually in `config/app.php`:

```
'providers' => [
    Tijanidevit\QueryFilter\Providers\FilterProvider::class,
]
```

---

Available Filters
-----------------

[](#available-filters)

### `filterBy()`

[](#filterby)

Filter by a column or multiple columns.

```
// Single column
User::query()->filterBy('status', 'active')->get();

// Multiple columns
User::query()->filterBy([
    'name' => 'Jane',
    'status' => ['active', 'pending'],
])->get();

// Handle null values
User::query()->filterBy([
    'email_verified_at' => ['null' => true],
])->get();
```

- Handles `null`, arrays, or empty values smartly.
- Fully chainable with other macros.

---

### `filterByRelation()`

[](#filterbyrelation)

Filter using related models:

```
Post::query()->filterByRelation([
    'user' => [
        'status' => 'active',
    ]
])->get();
```

Supports:

- Closures for advanced queries
- Nullable checks (`['null' => true]`)
- Standard operators: `['operator', 'value']`

---

### `filterWhereIn()`

[](#filterwherein)

Flexible `WHERE IN` filtering for single or multiple columns.

```
// Single column with array
User::query()->filterWhereIn('status', ['active', 'pending'])->get();

// Single column with multiple values as arguments
User::query()->filterWhereIn('status', 'active', 'pending')->get();

// Single column with comma-separated string
User::query()->filterWhereIn('status', 'active,pending')->get();

// Multiple columns with arrays
User::query()->filterWhereIn([
    'status' => ['active', 'pending'],
    'role' => ['admin', 'editor']
])->get();

// Multiple columns with comma-separated strings
User::query()->filterWhereIn([
    'status' => 'active,pending',
    'role' => 'admin,editor'
])->get();
```

- Automatically converts comma-separated strings into arrays.
- Skips empty or null values.
- Fully chainable.

---

### `filterByMonth()` / `filterByYear()`

[](#filterbymonth--filterbyyear)

Filter by month(s) or year(s):

```
Order::query()
    ->filterByMonth([1, 2]) // January and February
    ->filterByYear([2023, 2024])
    ->get();
```

- Accepts single value or array of values.
- Uses app timezone or configurable timezone and converts to UTC for queries.

---

### `filterByDate()`

[](#filterbydate)

Filter records by a single date:

```
User::query()->filterByDate('2024-01-01')->get();
```

- Converts to start and end of day automatically.
- Accepts optional timezone.

---

### `filterByDateRange()`

[](#filterbydaterange)

Filter records between two dates:

```
Order::query()->filterByDateRange('2024-01-01', '2024-03-01')->get();
```

- Accepts optional timezone.
- Works with either `dateFrom`, `dateTo`, or both.

---

### `filterFromRequest()`

[](#filterfromrequest)

Automatically apply filters from request input:

```
User::query()->filterFromRequest(request(), [
    'name' => 'name',
    'email' => 'email',
    'status' => 'status',
])->get();
```

- Accepts an array where keys are database columns and values are request keys.
- Skips empty or missing request values.

---

### `sortResultBy()`, `latestBy()`, `oldestBy()`

[](#sortresultby-latestby-oldestby)

Sort results easily:

```
User::query()->sortResultBy('created_at', 'desc')->get();

Post::query()->latestBy('published_at')->get();

Post::query()->oldestBy('published_at')->get();
```

---

### `search()` / `orSearch()` / `searchByRelation()`

[](#search--orsearch--searchbyrelation)

Search for patterns in columns:

```
// Search single column
User::query()->search('name', 'John')->get();

// Search multiple columns (OR)
User::query()->orSearch(['name', 'email'], 'John')->get();

// Search in a related model
Post::query()->searchByRelation('user', [
    'name' => 'John',
])->get();
```

- Default search uses SQL `LIKE %value%`.
- Supports relations, closures, and null checks.

---

Full Example
------------

[](#full-example)

```
$users = User::query()
    ->filterBy([
        'name' => request('name'),
        'status' => request('status'),
        'email_verified_at' => ['null' => request('missing_email_verification')],
    ])
    ->filterByRelation([
        'roles' => [
            'slug' => request('role_slug'),
        ],
    ])
    ->filterWhereIn([
        'department' => request('departments'), // array or comma-separated
        'status' => 'active,pending'
    ])
    ->filterByDateRange(request('from'), request('to'))
    ->sortResultBy(request('sort_by'), request('sort_dir', 'asc'))
    ->get();
```

---

💡 Tips &amp; Best Practices
---------------------------

[](#-tips--best-practices)

Query Filter macros are designed to be **fully chainable**, letting you compose complex queries cleanly. Here are some recommended patterns:

### 1. Combine `filterBy`, `filterWhereIn`, and `filterByRelation`

[](#1-combine-filterby-filterwherein-and-filterbyrelation)

```
$users = User::query()
    ->filterBy([
        'status' => request('status'),
        'email_verified_at' => ['null' => request('missing_email_verification')],
    ])
    ->filterWhereIn([
        'department' => request('departments'), // accepts array or comma-separated string
        'role' => 'admin,editor'
    ])
    ->filterByRelation([
        'manager' => [
            'status' => 'active',
        ],
    ])
    ->get();
```

- Use `filterBy` for simple columns with exact or nullable values.
- Use `filterWhereIn` when you want `IN` filtering, supporting arrays, comma-separated strings, or multiple arguments.
- Use `filterByRelation` to filter related models without manually writing `whereHas` queries.

---

### 2. Use `filterByDate` / `filterByDateRange` for date filtering

[](#2-use-filterbydate--filterbydaterange-for-date-filtering)

```
$orders = Order::query()
    ->filterByDate(request('date'))                     // exact day
    ->filterByDateRange(request('from'), request('to')) // range
    ->filterBy(['status' => request('status')])
    ->get();
```

- Supports optional timezone.
- Automatically converts dates to start and end of day in UTC for consistency.

---

### 3. Search with `search`, `orSearch`, and `searchByRelation`

[](#3-search-with-search-orsearch-and-searchbyrelation)

```
$posts = Post::query()
    ->search('title', request('title'))
    ->orSearch(['content', 'summary'], request('keyword'))
    ->searchByRelation('author', ['name' => request('author_name')])
    ->get();
```

- `search` is for a single column.
- `orSearch` allows searching across multiple columns.
- `searchByRelation` searches columns in related models.

---

### 4. Sorting and ordering

[](#4-sorting-and-ordering)

```
$users = User::query()
    ->filterBy(['status' => 'active'])
    ->sortResultBy(request('sort_by', 'created_at'), request('sort_dir', 'asc'))
    ->latestBy('last_login')
    ->get();
```

- Use `sortResultBy` for dynamic column sorting.
- Use `latestBy` or `oldestBy` for default chronological ordering.

---

### 5. Combining everything

[](#5-combining-everything)

For a full-featured admin or reporting query:

```
$users = User::query()
    ->filterBy([
        'status' => request('status'),
        'email_verified_at' => ['null' => request('missing_email_verification')],
    ])
    ->filterWhereIn([
        'department' => request('departments'),
        'role' => 'admin,editor'
    ])
    ->filterByRelation([
        'manager' => [
            'status' => 'active',
        ],
    ])
    ->filterByDateRange(request('from'), request('to'))
    ->orSearch(['name', 'email'], request('search'))
    ->sortResultBy(request('sort_by', 'created_at'), request('sort_dir', 'asc'))
    ->latestBy('last_login')
    ->get();
```

- Keep your queries readable and maintainable by chaining macros instead of nesting raw `where` and `orWhere` calls.
- The macros handle nulls, empty values, and type conversions, so your code stays clean.

---

### Recommendations

[](#recommendations)

1. **Always validate request inputs** before passing to filters if needed.
2. **Use arrays or comma-separated strings** with `filterWhereIn` for maximum flexibility.
3. **Combine macros in logical order**: `filterBy` → `filterWhereIn` → `filterByRelation` → `filterByDate/DateRange` → `search` → `sort`.
4. **Leverage `filterFromRequest`** for repetitive request-based filtering to simplify controllers.

This approach keeps your controllers slim and your queries consistent across the app.

```

---

## Requirements

- Laravel 9, 10, 11
- PHP 8.0+

---

## License

MIT © [Mustapha Tijani](mailto:thenewxpat@gmail.com)

---

## Contributing

Pull requests and issues are welcome. Help improve the package and make it more awesome!

```

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance74

Regular maintenance activity

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~24 days

Total

9

Last Release

173d ago

Major Versions

v0.0.8 → 1.0.02025-11-16

### Community

Maintainers

![](https://www.gravatar.com/avatar/7990aa5c55127a725703ec1f727df7ec221ab351acca47e00e8d6fb353275650?d=identicon)[tijanidevit](/maintainers/tijanidevit)

---

Top Contributors

[![tijanidevit](https://avatars.githubusercontent.com/u/57565055?v=4)](https://github.com/tijanidevit "tijanidevit (17 commits)")

### Embed Badge

![Health badge](/badges/tijanidevit-query-filter/health.svg)

```
[![Health](https://phpackages.com/badges/tijanidevit-query-filter/health.svg)](https://phpackages.com/packages/tijanidevit-query-filter)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M541](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M208](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
