PHPackages                             amirhshokri/laravel-filterable - 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. [Search &amp; Filtering](/categories/search)
4. /
5. amirhshokri/laravel-filterable

ActiveLibrary[Search &amp; Filtering](/categories/search)

amirhshokri/laravel-filterable
==============================

A better solution to add filter functionality to Laravel query builder.

v1.0.0(1y ago)1410MITPHPPHP ^8.1

Since Sep 9Pushed 10mo ago1 watchersCompare

[ Source](https://github.com/amirhshokri/laravel-filterable)[ Packagist](https://packagist.org/packages/amirhshokri/laravel-filterable)[ RSS](/packages/amirhshokri-laravel-filterable/feed)WikiDiscussions master Synced 1mo ago

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

Laravel filterable
==================

[](#laravel-filterable)

Introduction
------------

[](#introduction)

Laravel Filterable helps you add efficient filtering logic to the Laravel query builder. You can use the default filter logic, define custom filter logic manually, or create it using the provided command with any suffix in any path you choose. By enabling auto-discovery mode, the package will automatically locate the desired filter class for you.

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

[](#installation)

You can install the package via composer:

```
composer require amirhshokri/laravel-filterable
```

You can publish the config file with:

```
php artisan vendor:publish --tag="laravel-filterable-config"
```

This is the contents of the published config file:

```
return [
    'auto_discovery' => false,
    'namespace' => 'App\\Filterable\\Custom',
    'suffix' => 'Filter',
];
```

Basic usage
-----------

[](#basic-usage)

1 - Add the Filterable trait to your model.

```
use Amirhshokri\LaravelFilterable\Main\Filterable;

class User extends Authenticatable
{
    use Filterable;
}
```

2 - Add the `filter()` method to your query builder.

```
$users = \App\Models\User::query()
   ->filter()
   ->get();
```

3 - All set! Make a request:

```
{
  "filters": [
    {
      "name": "id",
      "operator": "isEqualTo",
      "value": 1
    },
    {
      "name": "email",
      "operator": "contains",
      "value": "@gmail"
    }
  ]
}
```

How to use `filter()` method?
-----------------------------

[](#how-to-use-filter-method)

### Method 1: Using default filter

[](#method-1-using-default-filter)

If you don’t provide a custom filter class for the `filter()` method and `auto-discovery` is turned off in the config file, the package will use the default filter functionality for your model, as explained previously in the [Basic usage](#basic-usage) section.

### Method 2: Passing a custom filter class

[](#method-2-passing-a-custom-filter-class)

You can pass a custom filter class to the `filter()` method to **enforce** specific filtering logic for your model:

```
$users = \App\Models\User::query()
   ->filter(new UserFilter())
   ->get();
```

- Create a custom filter class manually, or generate one using the following command:

```
php artisan make:filter  --path=Path\To\Filter\Class
```

- This command uses the `suffix` parameter from the config file to create the filter class. The file name must end with the specified suffix.
- If the `--path` option is not provided, the `namespace` parameter from the config file will be used as the default path.

Once you have created a custom filter class, you can extend the filtering logic for each field you wish to filter. Add a function in the custom filter class that corresponds to the `name` field in your request body:

```
use Amirhshokri\LaravelFilterable\Main\Filter\Custom\CustomFilter;

class UserFilter extends CustomFilter
{
    public function id($value, string $operator): void
    {
        //Custom filter logic here
    }

    public function email($value, string $operator): void
    {
        //Custom filter logic here
    }
}
```

- Each function can accept `$value` and `$operator` arguments. `$value` represents the value in the request, and `$operator` represents the operator.

### Method 3: Using auto-discovery

[](#method-3-using-auto-discovery)

When `auto-discovery` is enabled, this package will search for a filter class named `{ModelName}{Suffix}.php` using the `namespace` and `suffix` parameters defined in the config file. If the custom filter class is not found in the expected location, an exception will be thrown.

- If you don't want to use auto-discovery for a specific `filter()` call, you can use `setFilterAutoDiscovery(false)` before calling `filter()`:

```
$users = \App\Models\User::query()
   ->setFilterAutoDiscovery(false)
   ->filter()
   ->get();
```

### Method 4: Nested filters

[](#method-4-nested-filters)

In more complex scenarios, you can nest another `filter()` within your current filter logic to apply multiple conditions, such as filtering users based on their post titles. Make sure the Filterable trait is added to all relevant models:

```
use Amirhshokri\LaravelFilterable\Main\Filter\Custom\CustomFilter;

class UserFilter extends CustomFilter
{
    public function title($value, string $operator): void
    {
        $this->eloquentBuilder->whereHas('posts', function ($query) use ($value, $operator) {
            $query->setFilterParameters([
                    ['title', $operator, $value]
                ])->filter();
        });
    }
}
```

Additional Notes
----------------

[](#additional-notes)

1 - You can optionally specify which fields are allowed for filtering using the `$allowedFilterParameters` array. Leave it empty or omit it entirely to allow filtering on all fields:

```
use Amirhshokri\LaravelFilterable\Main\Filterable;

class User extends Authenticatable
{
    use Filterable;

    protected array $allowedFilterParameters = ['id', 'email'];
}
```

2 - Use the `operatorMapper()` method to map operators to their database equivalents:

**Supported Operator****Mapped Version**isEqualTo`=`isNotEqualTo`!=`greaterThan`>`lessThan`=`lessThanOrEqualTo`eloquentBuilder->where('mobile', $this->operatorMapper($operator), $value);
    }
}
```

3 - `OperatorEnum` can be used as needed:

```
use Amirhshokri\LaravelFilterable\Main\Filter\Custom\CustomFilter;
use Amirhshokri\LaravelFilterable\Main\Filter\Enum\OperatorEnum;

class UserFilter extends CustomFilter
{
    public function title($value, string $operator): void
    {
        $this->eloquentBuilder->whereHas('posts', function ($query) use ($value, $operator) {
            $query->setFilterParameters([
                    ['id', OperatorEnum::IS_NOT_EQUAL_TO, 10],
                    ['title', $operator, $value],
                    ['slug', OperatorEnum::CONTAINS, 'another pizza']
                ])->filter();
        });
    }
}
```

Credits
-------

[](#credits)

- [Amir Hossein Shokri](https://github.com/amirhshokri)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance46

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

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

Unknown

Total

1

Last Release

611d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/359d33664e45e8f2bba3aa7903e6c86a837371532679e5ffd184561afe2c23d8?d=identicon)[amirhshokri](/maintainers/amirhshokri)

---

Top Contributors

[![amirhshokri](https://avatars.githubusercontent.com/u/123773211?v=4)](https://github.com/amirhshokri "amirhshokri (45 commits)")

### Embed Badge

![Health badge](/badges/amirhshokri-laravel-filterable/health.svg)

```
[![Health](https://phpackages.com/badges/amirhshokri-laravel-filterable/health.svg)](https://phpackages.com/packages/amirhshokri-laravel-filterable)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[swisnl/laravel-fulltext

Fulltext indexing and searching for Laravel

184104.5k6](/packages/swisnl-laravel-fulltext)[orchestra/canvas

Code Generators for Laravel Applications and Packages

21017.2M158](/packages/orchestra-canvas)

PHPackages © 2026

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