PHPackages                             czim/laravel-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. czim/laravel-filter

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

czim/laravel-filter
===================

Filter for Laravel Eloquent queries, with support for modular filter building

5.0.2(1y ago)8973.0k↑12.5%14[2 issues](https://github.com/czim/laravel-filter/issues)3MITPHPPHP ^8.1

Since Sep 4Pushed 1y ago5 watchersCompare

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

READMEChangelog (1)Dependencies (8)Versions (26)Used By (3)

Laravel Filter
==============

[](#laravel-filter)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a149a3f10eb7b052d6a87ac9fe5767b1ab96113cedbecdc1f79a2f7026963b23/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f637a696d2f6c61726176656c2d66696c7465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/czim/laravel-filter)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/4c5937bc0dce6f18d557a9c8e328e30b6b591b2d0389cafce3c06bc98c58a790/68747470733a2f2f7472617669732d63692e6f72672f637a696d2f6c61726176656c2d66696c7465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/czim/laravel-filter)[![Latest Stable Version](https://camo.githubusercontent.com/e20a0306b098f333553023d2032bb5402d1b4f9de4ac3830559e90784248df77/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f637a696d2f6c61726176656c2d66696c7465722e737667)](https://packagist.org/packages/czim/laravel-filter)[![SensioLabsInsight](https://camo.githubusercontent.com/2f1ff5832add4c0771bf628d3c7a52c5a956169d12add58f60a4d5e3a1960b32/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f64376661346266332d346637392d343039352d396464612d6162623336313164396131632f6d696e692e706e67)](https://insight.sensiolabs.com/projects/d7fa4bf3-4f79-4095-9dda-abb3611d9a1c)

Configurable and modular Filter setup for Laravel. This is intended to make it easy to search for and filter by records using a typical web shop filter. For example, if you want to filter a catalog of products by product attributes, brand names, product lines and so forth.

The standard Filter class provided is set up to apply filters to a given (Eloquent) query builder. Additionally a CountableFilter extension of the class is provided for offering typical counts for determining what alternative filter settings should be displayed to visitors.

This is not a ready-to-use package, but a framework you can extend for your own specific applications.

Version Compatibility
---------------------

[](#version-compatibility)

LaravelPHPPackage5.8 and below7.0+1.16.0 to 7.07.1+2.06.0 to 8.07.2+3.19.08.1+4.010 and up8.1+5.0Changelog
---------

[](#changelog)

[Changelog here](CHANGELOG.md).

Install
-------

[](#install)

Via Composer

```
$ composer require czim/laravel-filter
```

Basic Usage
-----------

[](#basic-usage)

Make a class that extends `Czim\FilterData` and set the protected properties for validation rules `$rules` and the default values for these attributes `$defaults`. Note that `$defaults` are used as the main means to detect which filter parameters need to be applied to the query, so make sure all filter parameters you want to implement are present in it.

Simply extend the (abstract) filter class of your choice, either `Czim\Filter\Filter` or `Czim\Filter\CountableFilter`.

Each has abstract methods that must be provided for the class to work. Once they are all set (see below), you can simply apply filter settings to a query:

```
    $filterValues = [ 'attributename' => 'value', ... ];

    $filter = new SomeFilter($filterValues);

    // get an Eloquent builder query for a model
    $query = SomeEloquentModel::query();

    // apply the filter to the query
    $filteredQuery = $filter->apply($query);

    // normal get() call on the now filtered query
    $results = $filteredQuery->get();
```

A `CountableFilter` has an additional method that may be called:

```
    $countResults = $filter->count();
```

You can find more about countable filters below.

Filter Data
-----------

[](#filter-data)

You may pass any array or Arrayable data directly into the filter, and it will create a `FilterData` object for you. If you do not have the `$filterDataClass` property overridden, however, your filter will do nothing (because no attributes and defaults are set for it, the FilterData will always be empty). In your extension of the `Filter` class, override the property like so in order to be able to let the Filter create it automatically:

```
    class YourFilter extends \Czim\Filter\Filter
    {
        protected $filterDataClass = \Your\FilterDataClass::class;

        ...
    }
```

Your `FilterData` class should then look something like this:

```
    class FilterDataClass extends \Czim\Filter\FilterData
    {
        // Validation rules for filter attributes passed in
        protected $rules = [
            'name'   => 'string|required',
            'brands' => 'array|each:integer',
            'before' => 'date',
            'active' => 'boolean',
        ];

        // Default values and the parameter names accessible to the Filter class
        // If (optional) filter attributes are not provided, these defaults will be used:
        protected $defaults = [
            'name'   => null,
            'brands' => [],
            'before' => null,
            'active' => true,
        ];
    }
```

Filter validation rules are optional. If no rules are provided, validation always passes. Defaults are *required*, and define which parameter keys are applied by the filter.

Then, passing array(able) data into the constructor of your filter will automatically instantiate that FilterData class for you. If it is an (unmodified) extension of `Czim\FilterData`, it will also validate the data and throw an exception if the data does not match the `$rules` defined in your Data class.

Alternatively, you can make your own implementation of the provided `FilterDataInterface` and pass it into the Filter directly.

```
    $filter = new YourFilter( new YourFilterData($someData) );
```

All it needs to do is implement the interface; if you pass in data this way, the data will be set without any further checks or validation, unless you handle it in your FilterData implementation yourself.

Filters
-------

[](#filters)

Basic Filters take a query and apply filter parameters to it, before handing it back. (Note that the query object passed in will be modified; it is not cloned in the Filter before making modifications).

For example, if you'd do the following:

```
    $query = SomeModel::where('some_column', 1);

    $query = (new YourFilter([ 'name' => 'random' ]))->apply($query);

    echo $query->toSql();
```

You might expect the result to be something like `select * from some_models where some_column = 1 and name LIKE '%random%'`.

What a filter exactly does with the filter data you pass into its constructor must be defined in your implementation. This may be done in two main ways, which can be freely combined:

- By defining *strategies* (overriding the public `strategies()` method)
- By overriding the `applyParameter()` method as a fallback option

*Important*: filter logic is only invoked if the parameter's provided value is **not empty**. Regardless of the method you choose to make your filter application, it will *only* be applied if: `! empty($value) || $value === false`.

### Strategies and ParameterFilters

[](#strategies-and-parameterfilters)

You can define strategies for each filter parameter by adding a strategies method to your filter as follows:

```
    protected function strategies(): array
    {
        return [
            // as a ParameterFilter instance
            'parameter_name_here' => new \Czim\Filter\ParameterFilters\SimpleString(),

            // as a ParameterFilter class string
            'another_parameter'   => \Czim\Filter\ParameterFilters\SimpleString::class,

            // as an anonymous function
            'yet_another'         => function($name, $value, $query) {
                                        return $query->where('some_column', '>', $value);
                                     },

            // as an array (passable to call_user_func())
            'and_another'         => [ $this, 'someMethodYouDefined' ],
        ];
    }
```

If filter data is passed into the class with the same keyname as a strategy, that strategy method will be invoked. As shown above, there are different ways to provide a callable method for filters, but all methods mean passing data to a function that takes these parameters:

```
    /**
     * @param string          $name     the keyname of the parameter/strategy
     * @param mixed           $value    the value for this parameter set in the filter data
     * @param EloquentBuilder $query
     * @param FilterInterface $filter   the filter from which the strategy was invoked
     */
    public function apply(string $name, $value, $query);
```

A `ParameterFilter` is a class (any that implements the `ParameterFilterInterface`) which may be set as a filter strategy. The `apply()` method on this class will be called when the filter is applied. If the ParameterFilter is given as a string for the strategy, it will be instantiated when the filter is applied.

Strategies may also be defined as closures or arrays (so long as they may be fed into a `call_user_func()`). The method called by this will receive the four parameters noted above.

Only if no strategy has been defined for a parameter, the callback method `applyParameter()` will be called on the filter itself. By default, an exception will occur.

Some common ParameterFilters are included in this package:

- `SimpleInteger`: for looking up (integer) values with an optional operator ('=' by default)
- `SimpleString`: for looking up string values, with a *LIKE % + value + %* match by default
- `SimpleTranslatedString`: (uses `JoinKey::Translations` as the join key)

### The fallback option: applyParameter()

[](#the-fallback-option-applyparameter)

If you prefer, you can also use the fallback method to handle any or all of the appliccable parameters. Simply add the following method to your filter class:

```
    protected function applyParameter(string $name, $value, $query)
    {
        switch ($name) {

            case 'parameter_name_here':

                // your implementation of the filter ...
                return $query;

            ...
        }

        // as a safeguard, you can call the parent method,
        // which will throw exceptions for unhandled parameters
        parent::applyParameter($name, $value, $query);
    }
```

You can freely combine this approach with the strategy definitions mentioned above. The only limitation is that when there is a strategy defined for a parameter, the `applyParameter()` fallback will not be called for it.

Countable Filters
-----------------

[](#countable-filters)

The `CountableFilter` is an extension of the normal filter that helps write special filters for, say, web shops where it makes sense to show relevant alternatives based on the current filter choices.

Take a product catalog, for instance, where you're filtering based on a particular brand name and a price range. In the filter options shown, you may want to display other brands that your visitor can filter on, but *only* the brands for which your have products in the chosen price range. The idea is to prevent your visitors from selecting a different brand only to find that there are no results.

`CountableFilters` help you to do this, by using currently set filters to generate counts for alternative options. Say you have brand X, Y and Z, and are filtering products only for brand X and only in a given price range. The countable filter makes it easy to get a list of how many products also have matches for the price range of brand Y and Z.

To set up a `CountableFilter`, set up the `Filter` as normal, but additionally configure `$countables` and `countStrategies()`. The counting strategies are similarly configurable/implementable as filtering strategies.

The return value for `CountableFilter::count()` is an instance of `Czim\CountableResults`, which is basically a standard Laravel `Collection` instance.

### Counting Strategies

[](#counting-strategies)

Strategies may be defined for the effects of `count()` per parameter for your CountableFilter, in the same way as normal filter strategies.

```
    protected function countStrategies(): array
    {
        return [
            'parameter_name_here' => new \Czim\Filter\ParameterCounters\SimpleInteger(),
            ...
        ];
    }
```

The same methods for defining strategies are available as with the `strategies()` methods above: instances (of ParameterCounters in this case), strings, closures and arrays.

The fallback for parameters without defined strategies is `countParameter()`:

```
    /**
     * @param string          $parameter countable name
     * @param EloquentBuilder $query
     */
    protected function countParameter(string $parameter, $query)
    {
        // your implementation for each $parameter name
    }
```

### ParameterCounters

[](#parametercounters)

Just like ParameterFilters for `Filter`, ParameterCounters can be used as 'plugins' for your `CountableFilter`.

```
    protected function countStrategies(): array
    {
        return [
            'parameter_name_here' => new ParameterCounters\YourParameterCounter()
        ];
    }
```

ParameterCounters must implement the `ParameterCounterInterface`, featuring this method:

```
    /**
     * @param string                   $name
     * @param EloquentBuilder          $query
     * @param CountableFilterInterface $filter
     */
    public function count(string $name, $query, CountableFilterInterface $filter);
```

Settings and Extra stuff
------------------------

[](#settings-and-extra-stuff)

### Joins

[](#joins)

When joining tables for filter parameters, it may occur that different parameters require the same join(s). In order to prevent duplicate joining of tables, the Filter class has a built in helper for working with joins.

```
    // within your applyParameter implementation
    // the first parameter is a keyname you define, see the JoinKey enum provided
    // the second parameter is an array of parameters that is passed on directly
    //     to Laravel's query builder join() method.
    $this->addJoin('keyname_for_your_join', [ 'table', 'column_a', '=', 'column_b' ]);

    // or within a ParameterFilter apply() method, call it on the filter
    $filter->addJoin( ... , [ ... ]);
```

Joins so added are automatically applied to the filter after all parameters are applied.

### Global Filter Settings

[](#global-filter-settings)

Sometimes it may be useful to let filter-wide settings affect the way your filter works. You can set these through a setter directly on the filter class, `setSetting()`. Alternatively, you can define a filter parameter strategy as `Filter::SETTING`, and it will be loaded as a setting before the filter is applied.

```
    // in your Filter class:
    protected function strategies(): array
    {
        return [
            ...

            'global_setting_name' => static::SETTING
        ];
    }
```

When a setting has been set in either way, you can check it with the `setting()` method. Note that the ParameterFilter/ParameterCounter also receives the `$filter` itself as a parameter and the method is public.

If a setting has not been defined, the `setting()` method for it will return `null`.

Examples
--------

[](#examples)

Here are [some examples](EXAMPLES.md) of using the Filter and CountableFilter classes.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Coen Zimmerman](https://github.com/czim)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance48

Moderate activity, may be stable

Popularity45

Moderate usage in the ecosystem

Community21

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 87.5% 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 ~147 days

Recently: every ~235 days

Total

25

Last Release

378d ago

Major Versions

1.0.12 → 2.0.02019-09-18

1.0.x-dev → 3.0.02021-03-21

3.1.0 → 4.0.02022-10-06

4.0.1 → 5.0.02023-04-09

PHP version history (5 changes)1.0.0PHP &gt;=5.4.0

2.0.0PHP &gt;=7.1.8

3.0.0PHP &gt;=7.2

3.1.0PHP ^7.2|^8.0

4.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/1657b09521b6030fe32d864a493ded8b1dbbdf737ef3772135dfc123cea34767?d=identicon)[czim](/maintainers/czim)

---

Top Contributors

[![czim](https://avatars.githubusercontent.com/u/11831617?v=4)](https://github.com/czim "czim (28 commits)")[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (3 commits)")[![jovan-bl](https://avatars.githubusercontent.com/u/190348095?v=4)](https://github.com/jovan-bl "jovan-bl (1 commits)")

---

Tags

filterfilteringlaravellaravel-filterquery-builderlaraveldatabaseeloquentfilterfilters

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/czim-laravel-filter/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[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)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[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)
