PHPackages                             ameax/filter-core - 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. ameax/filter-core

ActiveLibrary

ameax/filter-core
=================

Type-safe filtering system for Laravel with 6 filter types, 18 match modes, AND/OR logic, relation filtering, and JSON serialization

00PHPCI failing

Since Nov 30Pushed 5mo agoCompare

[ Source](https://github.com/ameax/filter-core)[ Packagist](https://packagist.org/packages/ameax/filter-core)[ RSS](/packages/ameax-filter-core/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Filter Core
===========

[](#filter-core)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9f76784390e28cdb449b50e8ba060154bdb20d04e87d688175287487a312c2c0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616d6561782f66696c7465722d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ameax/filter-core)[![GitHub Tests Action Status](https://camo.githubusercontent.com/23f4a948a0a519fb3a59b85823b1813bf34048aeb46943faa842a66f2392119d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616d6561782f66696c7465722d636f72652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/ameax/filter-core/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/82007a4ae451dbd56c18f3cf2baca501f5d347e26b291388ddf03251275a21cc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616d6561782f66696c7465722d636f72652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/ameax/filter-core/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/014bb93d533dce44f87b1230843c27dacfbf3303f15292afc58f4c5d377dd1df/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616d6561782f66696c7465722d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ameax/filter-core)

A powerful, type-safe filtering system for Laravel applications. Filter Core provides a clean API for building complex database queries with automatic value sanitization, validation, and support for relations.

Features
--------

[](#features)

- **6 Filter Types**: Boolean, Integer, Text, Select, Date, Decimal filters
- **18 Match Modes**: IS, IS\_NOT, ANY, NONE, CONTAINS, GT, LT, BETWEEN, REGEX, EMPTY, DATE\_RANGE, and more
- **AND/OR Logic**: Complex nested filter groups with FilterSelection
- **Relation Filtering**: Filter through Eloquent relationships with `whereHas()`
- **Collection Filtering**: Apply the same filter logic to in-memory Collections
- **Date Filtering**: Quick selections, relative ranges, fiscal years, timezone support
- **Decimal Filtering**: Precision control, stored-as-integer support for prices
- **Quick Filter Presets**: Database-driven, user-configurable date range presets
- **Value Sanitization**: Automatic conversion of input values (e.g., `"true"` → `true`)
- **Value Validation**: Laravel validation rules with descriptive error messages
- **Dynamic Filters**: Create filters at runtime without class definitions
- **JSON Serialization**: Persist and restore filter configurations with optional model binding
- **Debugging Tools**: SQL preview, bindings interpolation, human-readable explanations

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

[](#installation)

```
composer require ameax/filter-core
```

Publish the migrations:

```
php artisan vendor:publish --tag="filter-core-migrations"
php artisan migrate
```

Optionally publish the config:

```
php artisan vendor:publish --tag="filter-core-config"
```

Quick Start
-----------

[](#quick-start)

### 1. Create a Filter

[](#1-create-a-filter)

```
use Ameax\FilterCore\Filters\SelectFilter;

class StatusFilter extends SelectFilter
{
    public function column(): string
    {
        return 'status';
    }

    public function options(): array
    {
        return [
            'active' => 'Active',
            'inactive' => 'Inactive',
            'pending' => 'Pending',
        ];
    }
}
```

### 2. Add Filterable Trait to Model

[](#2-add-filterable-trait-to-model)

```
use Ameax\FilterCore\Concerns\Filterable;

class User extends Model
{
    use Filterable;

    protected static function filterResolver(): \Closure
    {
        return fn () => [
            StatusFilter::class,
            CountFilter::class,
        ];
    }
}
```

### 3. Apply Filters

[](#3-apply-filters)

```
use Ameax\FilterCore\Data\FilterValue;

// Simple filter
$users = User::query()
    ->applyFilter(FilterValue::for(StatusFilter::class)->is('active'))
    ->get();

// Multiple filters with AND
$users = User::query()
    ->applyFilters([
        FilterValue::for(StatusFilter::class)->any(['active', 'pending']),
        FilterValue::for(CountFilter::class)->gt(10),
    ])
    ->get();
```

### 4. Use Filter Selections for Complex Logic

[](#4-use-filter-selections-for-complex-logic)

```
use Ameax\FilterCore\Selections\FilterSelection;
use Ameax\FilterCore\Selections\FilterGroup;

// AND logic (default)
$selection = FilterSelection::make()
    ->where(StatusFilter::class)->is('active')
    ->where(CountFilter::class)->gt(10);

// OR logic
$selection = FilterSelection::makeOr()
    ->where(StatusFilter::class)->is('active')
    ->where(StatusFilter::class)->is('pending');

// Nested: count > 10 AND (status = 'active' OR status = 'pending')
$selection = FilterSelection::make()
    ->where(CountFilter::class)->gt(10)
    ->orWhere(function (FilterGroup $g) {
        $g->where(StatusFilter::class)->is('active');
        $g->where(StatusFilter::class)->is('pending');
    });

$users = User::query()->applySelection($selection)->get();
```

### 5. Debug Your Filters

[](#5-debug-your-filters)

```
$selection = FilterSelection::make()
    ->forModel(User::class)
    ->where(StatusFilter::class)->is('active')
    ->where(CountFilter::class)->gt(10);

// SQL with placeholders
$selection->toSql();
// → "select * from `users` where `status` = ? and `count` > ?"

// SQL with values interpolated
$selection->toSqlWithBindings();
// → "select * from `users` where `status` = 'active' and `count` > 10"

// Human-readable explanation
$selection->explain();
// → "StatusFilter IS 'active' AND CountFilter GT 10"

// Full debug info
$selection->debug();
// → ['sql' => ..., 'sql_with_bindings' => ..., 'bindings' => [...], 'filters' => [...], 'explanation' => ...]
```

Documentation
-------------

[](#documentation)

GuideDescription[Getting Started](docs/guides/01-getting-started.md)Installation and basic setup[Filter Types](docs/guides/02-filter-types.md)All 6 filter types explained[Match Modes](docs/guides/03-match-modes.md)All 19 match modes explained[Filter Selections](docs/guides/04-filter-selections.md)AND/OR logic with nested groups[Relation Filters](docs/guides/05-relation-filters.md)Filter through relationships[Collection Filtering](docs/guides/06-collection-filtering.md)In-memory collection filtering[Dynamic Filters](docs/guides/07-dynamic-filters.md)Runtime filter creation[Validation](docs/guides/08-validation-sanitization.md)Input validation and sanitization[Advanced Usage](docs/guides/09-advanced-usage.md)Custom logic and extensibility[Date Filter](docs/guides/10-date-filter.md)Date filtering with timezone supportQuick Reference
---------------

[](#quick-reference)

### Filter Types

[](#filter-types)

TypeUse CaseKey Modes`SelectFilter`Predefined options`is`, `any`, `none``IntegerFilter`Numeric values`gt`, `lt`, `between``TextFilter`Text search`contains`, `startsWith`, `regex``BooleanFilter`True/False`is``DateFilter`Date/DateTime columns`dateRange`, `notInDateRange``DecimalFilter`Decimal/Float values`gt`, `lt`, `between`### Date Filter

[](#date-filter)

```
use Ameax\FilterCore\Filters\DateFilter;
use Ameax\FilterCore\DateRange\DateRangeValue;

// Static filter class
class CreatedAtFilter extends DateFilter
{
    public function column(): string
    {
        return 'created_at';
    }

    // Enable timezone conversion for DATETIME columns
    public function hasTime(): bool
    {
        return true;
    }
}

// Dynamic filter
$filter = DateFilter::dynamic('created_at')
    ->withColumn('created_at')
    ->withTime(); // DATETIME with timezone support

// Quick selections
DateRangeValue::today();
DateRangeValue::thisWeek();
DateRangeValue::thisMonth();
DateRangeValue::thisQuarter();
DateRangeValue::thisYear();

// Relative ranges
DateRangeValue::lastDays(30);
DateRangeValue::nextDays(7);
DateRangeValue::lastMonths(3);

// Specific periods
DateRangeValue::quarter(2, yearOffset: 0);  // Q2 this year
DateRangeValue::month(6, yearOffset: -1);   // June last year
DateRangeValue::fiscalYear(startMonth: 7);  // July-June fiscal year

// Custom ranges
DateRangeValue::between('2024-01-01', '2024-12-31');
DateRangeValue::from('2024-06-01');
DateRangeValue::until('2024-12-31');
```

### Decimal Filter

[](#decimal-filter)

```
use Ameax\FilterCore\Filters\DecimalFilter;

// For price columns stored as cents (integer)
class PriceFilter extends DecimalFilter
{
    public function column(): string
    {
        return 'price_cents';
    }

    public function storedAsInteger(): bool
    {
        return true; // User enters 19.99, query uses 1999
    }

    public function precision(): int
    {
        return 2;
    }
}

// Dynamic filter
$filter = DecimalFilter::dynamic('price')
    ->withColumn('price_cents')
    ->withStoredAsInteger(true)
    ->withPrecision(2);
```

### Match Modes

[](#match-modes)

```
// Equality
->is('value')           // = value
->isNot('value')        // != value

// Sets
->any(['a', 'b'])       // IN (a, b)
->none(['a', 'b'])      // NOT IN (a, b)

// Comparison
->gt(10)                // > 10
->gte(10)               // >= 10
->lt(100)               // < 100
->lte(100)              // between(10, 100)      // BETWEEN 10 AND 100

// Text
->contains('text')      // LIKE %text%
->startsWith('pre')     // LIKE pre%
->endsWith('fix')       // LIKE %fix
->regex('^pattern')     // REGEXP

// Null
->empty()               // IS NULL
->notEmpty()            // IS NOT NULL
```

### Relation Filters

[](#relation-filters)

```
// In filterResolver
protected static function filterResolver(): \Closure
{
    return fn () => [
        StatusFilter::class,                    // Direct filter
        CompanyStatusFilter::via('company'),    // Filter through relation
    ];
}

// Usage
User::query()
    ->applyFilter(FilterValue::for(CompanyStatusFilter::class)->is('active'))
    ->get();
```

### Dynamic Filters

[](#dynamic-filters)

```
use Ameax\FilterCore\Filters\SelectFilter;
use Ameax\FilterCore\Filters\DateFilter;
use Ameax\FilterCore\Filters\DecimalFilter;

// Select filter
$filter = SelectFilter::dynamic('status')
    ->withColumn('status')
    ->withOptions(['active' => 'Active', 'inactive' => 'Inactive']);

// Date filter with timezone
$filter = DateFilter::dynamic('created_at')
    ->withColumn('created_at')
    ->withTime()
    ->withPastOnly();

// Decimal filter for prices
$filter = DecimalFilter::dynamic('price')
    ->withColumn('price_cents')
    ->withStoredAsInteger(true)
    ->withPrecision(2);
```

### JSON Serialization

[](#json-serialization)

```
// Save
$json = $selection->toJson();

// Load
$selection = FilterSelection::fromJson($json);

// With model binding for self-validation and execution
$selection = FilterSelection::make('Active Users', User::class)
    ->where(StatusFilter::class)->is('active');

$json = $selection->toJson();
$restored = FilterSelection::fromJson($json);
$restored->validate();  // Self-validates against User model
$users = $restored->execute();  // Self-executes on User model
```

Configuration
-------------

[](#configuration)

```
// config/filter-core.php
return [
    // User model for FilterPreset ownership
    'user_model' => \App\Models\User::class,

    // Timezone for date/datetime filter queries
    // When filtering "today" in Europe/Berlin, converts to UTC for DB
    'timezone' => 'Europe/Berlin',
];
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

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

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Michael Schmidt](https://github.com/69188126+ms-aranes)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance48

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 95.2% 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/f67be86f330b5a3e644c8594bbf322be6ab1a08da5434d9cef417097d5567287?d=identicon)[aranes](/maintainers/aranes)

---

Top Contributors

[![ms-aranes](https://avatars.githubusercontent.com/u/69188126?v=4)](https://github.com/ms-aranes "ms-aranes (20 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

### Embed Badge

![Health badge](/badges/ameax-filter-core/health.svg)

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

PHPackages © 2026

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