koba/filter-builder-eloquent

Extension for the core filter builder library that allows applying filters on eloquent queries.

Maintainers

Package info

github.com/kobavzw/filter-builder-eloquent

pkg:composer/koba/filter-builder-eloquent

Statistics

Installs: 41

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.1 2026-02-23 21:35 UTC

This package is auto-updated.

Last update: 2026-03-23 21:53:43 UTC


README

Eloquent adapter for the filter-builder-core library.

Installation

composer require koba/filter-builder-eloquent

Usage

Creating an Eloquent Strategy

use App\Models\User;
use Koba\FilterBuilder\Core\Configuration\Configuration;
use Koba\FilterBuilder\Eloquent\EloquentStrategy;

$strategy = new EloquentStrategy(User::class);
$config = new Configuration($strategy);

Filtering Model Attributes

Use makeRule() to create filters for model attributes:

use Koba\FilterBuilder\Core\Enums\ConstraintType;
use Koba\FilterBuilder\Core\Enums\Operation;

$config->addRuleEntry(
    name: 'email',
    type: ConstraintType::STRING,
    supportedOperations: [Operation::EQUALS, Operation::STARTS_WITH],
    boundFilterFn: fn($strategy) => $strategy->makeRule(
        fn($query, $apply) => $apply('email', $query)
    )
);

Filtering Relationships

Use makeRelation() to filter based on related models:

use App\Models\Post;

// Create configuration for the related model
$postStrategy = new EloquentStrategy(Post::class);
$postConfig = new Configuration($postStrategy);

$postConfig->addRuleEntry(
    name: 'title',
    type: ConstraintType::STRING,
    supportedOperations: [Operation::STARTS_WITH],
    boundFilterFn: fn($strategy) => $strategy->makeRule(
        fn($query, $apply) => $apply('title', $query)
    )
);

// Add relationship filter
$config->addRelationEntry(
    name: 'posts',
    boundFilterFn: fn($strategy) => $strategy->makeRelation(
        Post::class,
        fn($query, $apply) => $query->whereHas('posts', $apply)
    ),
    configuration: $postConfig
);

Applying Filters

$filter = $config->getFilter($filterInput);

$query = User::query();
$filter->apply($query);

$users = $query->get();

Examples

Using whereDoesntHave

$config->addRelationEntry(
    name: 'posts',
    boundFilterFn: fn($strategy) => $strategy->makeRelation(
        Post::class,
        fn($query, $apply) => $query->whereDoesntHave('posts', $apply)
    ),
    configuration: $postConfig
);

Filtering on Relationship Attributes

$config->addRuleEntry(
    name: 'author_name',
    type: ConstraintType::STRING,
    supportedOperations: [Operation::EQUALS],
    boundFilterFn: fn($strategy) => $strategy->makeRule(
        fn($query, $apply) => $query->whereHas('author', fn($q) => $apply('name', $q))
    )
);

Documentation

For complete documentation on configuration, filter syntax, operations, and validation, see the core library.

License

MIT