PHPackages                             bahram/bfilters - 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. bahram/bfilters

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

bahram/bfilters
===============

A package for customized filtering on eloquent models

v1.14.1(1y ago)136155[2 PRs](https://github.com/alirezabahram7/bfilter/pulls)MITPHPPHP ^8.0|^8.1

Since Jul 7Pushed 1y ago1 watchersCompare

[ Source](https://github.com/alirezabahram7/bfilter)[ Packagist](https://packagist.org/packages/bahram/bfilters)[ RSS](/packages/bahram-bfilters/feed)WikiDiscussions master Synced 1mo ago

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

Bahram Filter
=============

[](#bahram-filter)

Apply auto filters to Eloquent models.
Using this package, easily apply filters, sorting and pagination to Eloquent models and their relations, with query string parameters.

### Requirements

[](#requirements)

php: `^8.0|^8.1`
laravel: `>=8.0`

For miner php|Laravel versions use other releases.

### Installation

[](#installation)

```
composer require bahram/bfilters

```

### Use HasFilter Trait On your Eloquent Models

[](#use-hasfilter-trait-on-your-eloquent-models)

Your models should use the `HasFilter` trait:

```
use BFilters\Traits;

class MyModel extends Eloquent
{
    use HasFilter;

    // Add columns which you want to use for "full text serach" in "searchable" or "fillable" array
    protected $searchable = [
    'first_name',
    'last_name'
    ];
}

```

### Create Filter Class

[](#create-filter-class)

```
php artisan make:filter {name}

```

for example:

```
php artisan make:filter UserFilter

```

### In your Created Filter Class :

[](#in-your-created-filter-class-)

```
use Illuminate\Http\Request;

class UserFilter extends Filter
{
    public function __construct(Request $request)
    {
        parent::__construct($request);

        $this->relations = [

            //Add the actual name of the relation function that is defined in the original model
            'relationName1' => [
                'searchName1' => 'Original column1 Name in Relation table',
                'searchName2' => 'Original column2 Name in Relation table',
                'searchName3' => 'Original column3 Name in Relation table',

                //if searchName and original column name is the same :
                'Original column4 Name in Relation table'
            ],

            'posts' => [

                // in this case when you set posted_at as your filter the filter will applied on 'created_at' field of original table
                'posted_at' => 'created_at',
                'title',
                'topic',
            ],
        ];

        $this->jsonFields = [

            //Add the actual name of the json column
            'jsonColumn1' => [
                'searchName1' => 'Original field Name 1 in JsonColumn1',
                'searchName2' => 'Original field Name 2 in JsonColumn1',

                //if searchName and original column name is the same :
                'Original field Name 3 in JsonColumn3'
            ],
        ];

        // set this variabe if you want to have sum of your entries based on a specific column (f.e 'amount')
        $this->sumField = 'amount';

        // define valid eager loading relations to prevent loading unwanted data
        $this->validWiths = ['comments', 'tags'];
    }
}

```

### Usage

[](#usage)

In controllers :

```
public function index(YourModelFilter $filters): Response
{
    [$entries, $count, $sum] = YourModel::filter($filters);
    return ($entries->get());
}

```

In Api Request Query String :

```
filter:{
        "sort":[
                { "field": "created_at", "dir": "asc" },
                { "field": "first_name", "dir": "desc" }
         ],
         "page":{ "limit": 10, "offset": 0 },
         "filters":[

                    //(first_name LIKE '%alireza%' or last_name = '%bahram%') and (mobile LIKE '%9891%')
                    [
                       //use "or" for fields in same array & use "and" for fields in different array
                       {"field": "first_name", "op": "like", "value":  "alireza"},
                       {"field": "last_name", "op": "=", "value":  "bahram"}
                    ],

                    //(mobile LIKE '%9891%')
                    [
                        {"field": "mobile", "op": "like", "value": "9891"}
                    ],

                    [
                        //full text search : search a string on columns you set in its model "searchable" or "fillable" arrays
                        {"value" : "al"}
                    ]
         ],
         "with":[
            "comments",
            "tags"
         ]
}

```

\###Add Validation Rules

\####To validate filters before applying it, add this method to your filter class:

```
public function rules()
{
    return [
        'id' => 'int|required',
        'user_id' => 'exists:users,id'
    ];
}

```

If you need custom filter on relation : (For example array search in postgresql) :
----------------------------------------------------------------------------------

[](#if-you-need-custom-filter-on-relation--for-example-array-search-in-postgresql-)

In Request

```

class MessageFilter extends Filter
{
    public function __construct(Request $request)
    {
        $this->relations = [
            "packages" => [
                "numbers" => function ($query, $filter) {
                    $query->whereRaw("'{$filter->value}' {$filter->op} ANY(numbers)");
                },
            ],
            "line" => [
                "line_number" => "number",
            ],
        ];

        //$this->sumField = null;
        $this->validWiths = ["packages"];

        parent::__construct($request);
    }
}

```

Json Search:
------------

[](#json-search)

Assume you have a json column named address like this :

```
{
"city" : "tehran",
"Street" : "jordan"
}

```

So you Can simply add Your Json Column(s) to your filter class, like this:

```
class UserFilter extends Filter
{
    public function __construct(Request $request)
    {
      $this->jsonFields = [
            "address" => ["city_name" => "city",
                            "street_name" => "street
                            ]
        ];

        parent::__construct($request);
    }
}

```

Then you can apply filters on your Model as simple as this :

`filter:{"filters":[[{"field":"city_name","op":"=","value":"tehran"}],[{"field":"street_name","op":"=","value":"jordan"}]]}`

Query String Samples:
---------------------

[](#query-string-samples)

### pagination: per\_page=10 :

[](#pagination-per_page10-)

`?filter={"page":{"limit": 10,"offset": 0}}`

### pagination per\_page=20 and (ordered by `id` desc) :

[](#pagination-per_page20-and-ordered-by-id-desc-)

`?filter={"page":{"limit":20,"offset":0},"sort":[{"field":"id","dir":"desc"}]}`

### add a filter : name like john :

[](#add-a-filter--name-like-john-)

`?filter={"page":{"limit":20,"offset":0},"sort":[{"field":"id","dir":"desc"}],"filters":[[{"field":"name","op":"like","value":"john"}]]}`

### (first\_name like alireza `or` last name like bahram) `and` (email = )

[](#first_name-like-alireza-or-last-name-like-bahram-and-email--alib327gmailcom)

```
?filer={
        "page":{"limit":20,"offset":0},
        "sort":[{"field":"id","dir":"desc"}],
        "filters":[
                    [
                        {"field": "first_name", "op": "like", "value":  "alireza"},
                        {"field": "last_name", "op": "=", "value":  "bahram"}
                    ],
                    [
                        {"field": "email", "op": "=", "value":  "09196649497"},
                    ],
                   ]
        }

```

### you can use `magic filters` as well:

[](#you-can-use-magic-filters-as-well)

without using `field`,`op`, and `value`(email = ):

```
?filer={
        "page":{"limit":20,"offset":0},
        "sort":[{"field":"id","dir":"desc"}],
        "filters":
                    [
                        ["email","09196649497"],
                    ],

```

### full Text Search:

[](#full-text-search)

```
?filer={
        "page":{"limit":20,"offset":0},
        "sort":[{"field":"id","dir":"desc"}],
        "filters":
                    [
                        {"value":"alireza"},
                    ],

```

\##Basic Methods

### Use Make Filter class to make a custom filter on an Api call

[](#use-make-filter-class-to-make-a-custom-filter-on-an-api-call)

For example assume a function within your controller:

```
public function showUserArticles($userId)
    {
        $filters = new MakeFilter();
        $filters->orderBy('posted_at', 'desc');
        $filters->addFilter([
            [
                'field' => 'user_id',
                'op' => '=',
                'value' => $userId
            ]
        ]);
        return Http::get(Put your URL here, [
            'filter' => $filters->toJson()
        ]);
    }

```

### Edit given request filters

[](#edit-given-request-filters)

```
public function Index(UserFilter $filters)
    {
        $filters->removeFilter('first_name')->removePagination();
    }

```

### "addMagicFilter" method

[](#addmagicfilter-method)

```
     $filters->removeFilter('first_name')->removePagination()
                ->addMagicFilter([
                                    [
                                        'user_id',
                                         $userId
                                    ]
                                ]);

```

### "addOrder" method

[](#addorder-method)

```
$filters->[
                'field' => 'posted_at',
                'dir' => 'desc'
            ];

```

### use "setFilters" method to set multiple filters

[](#use-setfilters-method-to-set-multiple-filters)

```
    $filters->setFilters([
    [
        [
        'field' => 'user_id',
        'op' => '=',
        'value' => $userId
        ],
        [
        'field' => 'user_name',
        'op' => '=',
        'value' => $userName
        ]
    ]]);

```

### use "getFilters" method to get the applied filters as an array

[](#use-getfilters-method-to-get-the-applied-filters-as-an-array)

```
$filters->getFilters();

```

### use "getFilter" method to get a specific filter

[](#use-getfilter-method-to-get-a-specific-filter)

```
$filters->getFilter('first_name');

```

### use "setWiths" method to eager loads some specific relations of the model

[](#use-setwiths-method-to-eager-loads-some-specific-relations-of-the-model)

```
$filters->setWiths(['posts, 'comments']);

```

### use "getWiths" method to get relations already set on given filters

[](#use-getwiths-method-to-get-relations-already-set-on-given-filters)

```
$filters->getWiths();

```

### use "setPage" method to set pagination on filters

[](#use-setpage-method-to-set-pagination-on-filters)

```
$filters->setPage(
                    [
                        "limit" => 20,
                        "offset"=> 100
                    ]
                  );

```

### use "getPage" method to get pagination already applied to the given request

[](#use-getpage-method-to-get-pagination-already-applied-to-the-given-request)

```
$filters->getPage();

```

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 71.3% 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 ~41 days

Recently: every ~117 days

Total

39

Last Release

560d ago

PHP version history (6 changes)v1.0.1PHP ^7.0

1.1.0PHP ^7.2|^7.3|^7.4

1.4.1PHP ^7.2|^7.3|^7.4|^8.0

1.5.3PHP ^7.4|^8.0

v1.10.0PHP ^7.4|^8.0|^8.1

1.11.0PHP ^8.0|^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/9839562f9347b89b5d17729afda335867742cd4a7880285814dcba580d8e3ed6?d=identicon)[alirezabahram](/maintainers/alirezabahram)

---

Top Contributors

[![alirezabahram7](https://avatars.githubusercontent.com/u/46995989?v=4)](https://github.com/alirezabahram7 "alirezabahram7 (114 commits)")[![Hebrahimzadeh](https://avatars.githubusercontent.com/u/38420287?v=4)](https://github.com/Hebrahimzadeh "Hebrahimzadeh (31 commits)")[![geeksesi](https://avatars.githubusercontent.com/u/28778964?v=4)](https://github.com/geeksesi "geeksesi (6 commits)")[![saber13812002](https://avatars.githubusercontent.com/u/3294604?v=4)](https://github.com/saber13812002 "saber13812002 (4 commits)")[![meysamfard](https://avatars.githubusercontent.com/u/39233907?v=4)](https://github.com/meysamfard "meysamfard (2 commits)")[![mhabedini](https://avatars.githubusercontent.com/u/13943537?v=4)](https://github.com/mhabedini "mhabedini (1 commits)")[![omalizadeh](https://avatars.githubusercontent.com/u/12392549?v=4)](https://github.com/omalizadeh "omalizadeh (1 commits)")[![devilinfamous-bot](https://avatars.githubusercontent.com/u/252126803?v=4)](https://github.com/devilinfamous-bot "devilinfamous-bot (1 commits)")

### Embed Badge

![Health badge](/badges/bahram-bfilters/health.svg)

```
[![Health](https://phpackages.com/badges/bahram-bfilters/health.svg)](https://phpackages.com/packages/bahram-bfilters)
```

###  Alternatives

[ruflin/elastica

Elasticsearch Client

2.3k50.4M203](/packages/ruflin-elastica)[opensearch-project/opensearch-php

PHP Client for OpenSearch

15024.3M65](/packages/opensearch-project-opensearch-php)[mailerlite/laravel-elasticsearch

An easy way to use the official PHP ElasticSearch client in your Laravel applications.

934529.3k2](/packages/mailerlite-laravel-elasticsearch)[massive/search-bundle

Massive Search Bundle

721.4M13](/packages/massive-search-bundle)[shyim/opensearch-php-dsl

OpenSearch/Elasticsearch DSL library

175.9M9](/packages/shyim-opensearch-php-dsl)[outl1ne/nova-multiselect-filter

Multiselect filter for Laravel Nova.

45802.7k3](/packages/outl1ne-nova-multiselect-filter)

PHPackages © 2026

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