PHPackages                             laravellegends/eloquent-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. laravellegends/eloquent-filter

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

laravellegends/eloquent-filter
==============================

A simple Eloquent filter to make easy API filtering

3.0.4(3y ago)4018.6k↓35%8MITPHP

Since Oct 16Pushed 2y ago4 watchersCompare

[ Source](https://github.com/LaravelLegends/eloquent-filter)[ Packagist](https://packagist.org/packages/laravellegends/eloquent-filter)[ RSS](/packages/laravellegends-eloquent-filter/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (20)Used By (0)

Laravel Legends Eloquent Filter
===============================

[](#laravel-legends-eloquent-filter)

A useful library to make filters for Eloquent.

This library is useful to create search filters in your Rest API using the Eloquent.

🇧🇷🚀🚀🚀

Description
-----------

[](#description)

The Eloquent Filter library can be used to create patterns for search criterias on models in your Laravel Project. The idea is aggregate filters simply passing the values in your request payload.

Instalation
-----------

[](#instalation)

For instalation, you should be use Composer. Run the follow command:

`composer require laravellegends/eloquent-filter`

Usage guide
-----------

[](#usage-guide)

The `LaravelLegends\EloquentFilter\Concerns\HasFilter` trait can be used in models that will be apply the search filters.

```
use LaravelLegends\EloquentFilter\Concerns\HasFilter;

class User extends Model
{
    use HasFilter;
}
```

The `HasFilter` trait provides the `filter` and `withFilter` methods.

A simple way to use this library in your Laravel application is calling the `filter` method before get results of your model.

Example:

```
class UsersController extends Controller
{
    use App\Models\User;

    public function index()
    {
        return User::filter()->paginate();
    }

    // or

    public function index()
    {
        return User::latest('id')->filter()->paginate();
    }

    // or

    public function index(Request $request)
    {
        return User::filter($request)->paginate();
    }
}
```

You can show the results when call `/api/users?exact[id]=1`. The sql query `"select * from users where (id = 1)"` will be applied.

Note: Show the [rules](#max) session to more information.

Another way, is using the specific filter for a model. You can inherit the ModelFilter class to create a custom filter for a model.

For create this class, you should be use the command `php artisan make:filter`, as follow example:

```
$ php artisan make:filter UserFilter
```

The above command will be generate the follow class:

```
namespace App\Filters;

use LaravelLegends\EloquentFilter\Filters\ModelFilter;

class UserFilter extends ModelFilter
{
    public function getFilterables(): array
    {
        return [
            'role_id' => 'not_equal', // or ['not_equal']
            'name'    => ['contains', 'starts_with'],
        ];
    }
}
```

In Controller

```
use App\Models\User;
use Illuminate\Http\Request;
use LaravelLegends\EloquentFilter\Filter;

class UsersController extends Controller
{
    // api/users?starts_with[name]=Wallace&not_equal[role_id]=2

    public function index(Request $request)
    {
        return User::withFilter(new UserFilter, $request)
                    ->orderBy('name')
                    ->get();
    }
}
```

The above code internally will be called as follow example:

```
User::where(function ($query) {
    $query->where('name', 'LIKE', 'Wallace%');
    $query->where('role_id', '', '2');
})
->orderBy('name')
->get();
```

---

What does it do?
----------------

[](#what-does-it-do)

This library internally apply filters based on query string parameters with special keyworks names.

See all paramaters follow:

max
---

[](#max)

The maximum value of a column. The url `api/users?max[field]=100` is like a `User::where('field', '=', 33)`.

---

contains
--------

[](#contains)

A search term contained in a column. The url `api/users?contains[name]=wallace` is like a `User::where('name', 'LIKE', '%wallace%')`.

---

ends\_with
----------

[](#ends_with)

Search a value according to end content of string. Is similar to a `LIKE` with `%$value` value.

---

starts\_with
------------

[](#starts_with)

Filter the field when the value starts with a certain value. A url `api/users?starts_with[name]=brcontainer` Sounds like a `User::where('name', 'LIKE', 'brcontainer%')`.

---

exact
-----

[](#exact)

Search by a exact value of the field· A url `api/users?exact[email]=teste@teste.com` Sounds like a `User::where('name', '=', 'teste@teste.com')`.

---

has
---

[](#has)

Filter by relationship. You can use the `0` or `1` value.

Example:

The url `api/users?has[posts]=1` is like a `User::has('posts')`

The url `api/users?has[posts]=0` is like a `User::doesntHave('posts')`

---

is\_null
--------

[](#is_null)

Apply `WHERE IS NULL` or `WHERE IS NOT NULL` to a query.

Example:

The url `api/users?is_null[cpf]=1` is like a `User::whereNull('cpf')`

The url `api/users?is_null[age]=0` is like a `User::whereNotNull('age')`

---

not\_in
-------

[](#not_in)

Searchs when a column NOT HAS the passed values.

Example:

A url `api/users?not_in[role][]=1&not_in[role][]=2` é equivalente à `User::whereNotIn('role', [1, 2])`

**Note**: When the `not_in[my_field]` is a empty array, no action will be taken.

---

in
--

[](#in)

Searchs when a column HAS the passed values.

Example:

The url `api/users?in[role][]=10&in[role][]=20` sounds like a `User::whereIn('role', [10, 20])`

**NOTE**: When the `in[my_field]` is a empty array, no action will be taken.

---

date\_max
---------

[](#date_max)

Search by a maximium value of a date field.

A url `api/users?date_max[created_at]=2021-01-01` sounds like a `User::whereDate('created_at', '=', '2021-01-01')`

---

not\_equal
----------

[](#not_equal)

Search by not equal value passed. If you use in related field, the whereDoesntHave will be applied applied.

Example:

The url `api/users?not_equal[profile_id]=3` sounds like a

```
User::where('profile_id', '', '3');
```

The url `api/users?not_equal[roles.id]=1` sounds like a

```
User::whereDoesntHave('roles', fn ($query) => $query->where('id', '=', 3));
```

---

year\_max
---------

[](#year_max)

The url `api/users?year_max[created_at]=2000` sounds like a

```
User::whereYear('created_at', '=', 1998);
```

---

year\_exact
-----------

[](#year_exact)

The url `api/users?year_exact[created_at]=1998` sounds like a

```
User::whereYear('created_at', '=', 1998);
```

---

Filtering relationship fields
-----------------------------

[](#filtering-relationship-fields)

You can apply the search filters in the relatioship methods defined in your model.

For example:

Model:

```
class User extends Model
{
    use HasFilter;

    public function phones()
    {
        return $this->hasMany(Phone::class, 'user_id');
    }
}
```

Filters:

```
class UserFilter extends ModelFilter
{
    public function getFilterables(): array
    {
        return [
            'id'            => ['exact', 'not_equal'],
            'created_at'    => ['year_exact', 'date_max', 'date_min'],
            'phones.number' => ['contains'],
            // or
            'phones'        => new PhoneFilter,
        ];
    }
}

class PhoneFilter extends ModelFilter
{

    public function getFilterables(): array
    {
        return [
            'number' => 'contains'
        ];
    }
}
```

```
class UserController extends Controller
{
    public function index()
    {
        // api/users?not_in[role_id][]=1&not_in[role_id][]=3

        // select * from users where (role_id NOT IN (1, 3))

        return User::withFilter(new UserFilter)->paginate();
    }

    // Or, apply filter as nested query

    public function index()
    {

        // api/users?exact[role_id]=1

        // select * from users where (role_id = 1)

        return User::where(UserFilter::toClosure())->paginate();
    }

    // Or apply in your query as base condition

    public function index()
    {

        // api/users?exact[role_id]=1

        // select * from users where role_id = 1

        return User::tap(UserFilter::toClosure())->paginate();
    }
}
```

In the following example, the user will be filtered for the related phone containing the value `55`.

The `api/users?exact[phones.number]=55` is like to:

```
User::where(function ($query) {
    $query->whereHas('phones', function ($query) {
        $query->where('number', '=', '55');
    });
})->paginate();
```

Axios examples
--------------

[](#axios-examples)

If you use `axios` library, you can use the `params` options to include the above filters.

Example:

```
const api = axios.create({
    baseURL: 'http://localhost:8000/api'
});

api.get('users', {
    params: {
        'in[role]' : [1, 2, 3],
        'contains[name]' : 'Maxters',
        'is_null[name]' : 0
    }
})
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity66

Established project with proven stability

 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 ~55 days

Total

19

Last Release

1405d ago

Major Versions

1.0.2 → 2.0.02021-02-03

2.2.4 → 3.0.02021-11-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/983cda3e30a5a58d250f3bef7360267e0185b46e891f2f08e6683d0af9a9ddc7?d=identicon)[wallacemaxters](/maintainers/wallacemaxters)

---

Top Contributors

[![wallacemaxters](https://avatars.githubusercontent.com/u/5245865?v=4)](https://github.com/wallacemaxters "wallacemaxters (99 commits)")

---

Tags

eloquentfilterlaravelsearchsearchlaraveleloquentfilter

### Embed Badge

![Health badge](/badges/laravellegends-eloquent-filter/health.svg)

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

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[mohammad-fouladgar/eloquent-builder

527189.5k](/packages/mohammad-fouladgar-eloquent-builder)[mehdi-fathi/eloquent-filter

Eloquent Filter adds custom filters automatically to your Eloquent Models in Laravel.It's easy to use and fully dynamic, just with sending the Query Strings to it.

450191.6k1](/packages/mehdi-fathi-eloquent-filter)[jedrzej/searchable

Searchable trait for Laravel's Eloquent models - filter your models using request parameters

127259.1k5](/packages/jedrzej-searchable)[lacodix/laravel-model-filter

A Laravel package to filter, search and sort models with ease while fetching from database.

17649.9k](/packages/lacodix-laravel-model-filter)[aldemeery/sieve

A simple, clean and elegant way to filter Eloquent models.

1396.3k](/packages/aldemeery-sieve)

PHPackages © 2026

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