PHPackages                             freebuu/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. freebuu/laravel-filterable

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

freebuu/laravel-filterable
==========================

Model filters for your index requests

1.1.0(2mo ago)051MITPHPPHP ^8.1CI passing

Since Apr 25Pushed 2mo ago1 watchersCompare

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

READMEChangelog (3)Dependencies (14)Versions (6)Used By (0)

Laravel Filterable
==================

[](#laravel-filterable)

Simple filter and paginate index data. Main idea - KISS.

Example query:

```
?search_description=some%20text&sort_id=desc&where_publisher_id=1,23&where_has_groups__id=30,40&limit=10&offset=20

```

In code this query reflects:

- **search\_description=some%20text** - `$builder->where('description', 'like', '%some%text%')`
- **sort\_id=desc** - `$builder->sortBy('id', 'desc')`
- **where\_publisher\_id=1,23** - `$builder->whereIn('publisher_id', [1,23])`
- **where\_has\_groups\_\_id=30,40** - `$builder->whereHas('groups', fn($builder) => $builder->whereIn('id', [30,40]))`
- **limit=10** - `$builder->limit(10)`
- **offset=20** - `$builder->offset(20)`

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

[](#installation)

Requires laravel &gt;= 9 and php ^8.1

```
composer require freebuu/laravel-filterable
```

Basic usage (pagination only)
-----------------------------

[](#basic-usage-pagination-only)

Add [HasRequestFilter](src/HasRequestFilter.php) trait to Model - that's all.

```
class PostIndexController
{
    public function __invoke(Request $request): JsonResponse
    {
        return Post::requestFilter()->jsonResponse(PostResource::class)
    }
}
```

Example result for query `/api/posts/?limit=25&offset=10`

```
{
    "meta": {
        "limit": 25,
        "offset": 10,
        "total": 2
    },
    "data": [
        {
            "id": "1",
            "title": "post title"
        },
        {
            "id": "2",
            "title": "another post title"
        }
    ]
}
```

- `meta` - object with pagination data
- `data` - array with model data, wrapped in `PostResource`

Filtration
----------

[](#filtration)

For filtration, you need to create a filter class for each model. Filter class must extend [AbstractFilter](src/AbstractFilter.php). Best place for these classes is `App\Http\Filters`.

In method `getFilterableFields()` you specify which fields can be filtered in each filter case.

***HINT*** - always add `default` state because filter cases may be supplemented.

```
class PostFilter extends AbstractFilter
{
    protected function getFilterableFields(FilterCaseEnum $case): array
    {
        return match ($case) {
            FilterCaseEnum::WHERE => ['publisher_id'],
            FilterCaseEnum::SORT => ['id'],
            FilterCaseEnum::WHERE_HAS => ['groups' => ['id']]
            default => []
        };
    }
}
```

To set this filter for `Model` - add property `requestFilter`

```
class Post extends Model
{
    use HasRequestFilter;

    protected string $requestFilter = PostFilter::class;
}
```

### Filter case

[](#filter-case)

Filterable query params contains four parts separated with `_`. Let's see example with `where_has_groups__id=30,40`

- **$case** - where\_has
- **$field** - groups
- **$fieldValue** - id (optional, mandatory only with **where\_has**)
- **$value** - 30,40

In code, they are presented as [FilterCaseEnum.php](src/Params/FilterCaseEnum.php) and they work like this

- **FROM**
    - Accepts only int
    - `$builder->where($field, '>=', $value)`
- **TO**
    - Accepts only int
    - `$builder->where($field, 'where($field', 'like', $value)`
- **WHERE\_HAS** - filter by relation with array of values
    - Accept comma separated array of values.
    - For this filter `fieldValue` fields must be set (see in example in `PostFilter`)
    - `$builder->whereHas($field, fn($builder) => $builder->whereIn($fieldValue, $value))`
- **WHERE** - filter by array of values
    - Accept comma separated array of values.
    - `$builder->whereIn($fieldValue, $value)`
- **FILTER** - uses for custom filters, see below

### Custom filters

[](#custom-filters)

In filter class you can make custom filter by creating a method like `filterCustom` - it **must** begin with `filter`. Then yoy can use it in query like `?filter_custom=123`

***HINT*** - you can use `fieldValue` here like `?filter_custom__alias=123` - it pass as third parameter in filter method.

```
class PostFilter extends AbstractFilter
{
    public function filterCustom(Builder $builder, mixed $value, mixed $fieldValue): void
    {
        //you have request instance here
        if($this->request->query('something')){
            return;
        }
        //$value will be 123
        //$fieldValue will be alias (or can be null)
        $builder->where('some_field', $value)->where($fieldValue, '432')
    }
}
```

Advanced usage
--------------

[](#advanced-usage)

Limit
-----

[](#limit)

For security reasons, the `limit` field is set to a maximum value. If the request specifies a value greater, it will be reset to the default value.

- Default it set to `30`
- You can override this value in Filter class - overwrite the `maxLimit` property.
- Or you can override it system-wide in `AppServiceProvider`

```
class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        AbstractFilter::$defaultMaxLimit = 50;
    }
}
```

Query callbacks
---------------

[](#query-callbacks)

Sometimes you need to set up query condition situational—e.g. filter only for auth user

```
Post::requestFilter()
    ->addQueryCallback(fn (Builder $builder) => $builder->where('author_id', auth()->id()))
    ->response(ResourceClass::class);
```

Or just use `Builder` mixin:

```
Post::requestFilter()
    ->where('author_id', auth()->id())
    ->response(ResourceClass::class);
```

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance87

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

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

Total

5

Last Release

64d ago

Major Versions

0.0.1 → 1.0.02025-11-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/46676bc740c501a0eaf765875d496f7a19db0009d0fd83f0981d0cad0b8270c2?d=identicon)[freebuu](/maintainers/freebuu)

---

Top Contributors

[![freebuu](https://avatars.githubusercontent.com/u/9998200?v=4)](https://github.com/freebuu "freebuu (33 commits)")

---

Tags

laravellaravel filterlaravel-filterablerequest filter

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[kyslik/laravel-filterable

Using URL query strings to filter Eloquent queries.

11539.0k](/packages/kyslik-laravel-filterable)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

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