Latest Version on PackagistTotal DownloadsGitHub Stars
PHP Version RequireLaravel Version Require
GitHub Tests Action StatusCodecov

Overview

Eloquent Filtering simplifies implementing search functionality for your Eloquent models, whether simple or complex, by eliminating the need for custom query logic. It allows you to easily define and manage filters directly within your models, and seamlessly apply them using incoming HTTP request data to dynamically filter your models.

With this package, you can build more readable, maintainable, and scalable code, boosting your productivity and speeding up development.

Whether you’re building APIs, dashboards, or advanced search systems, Eloquent Filtering provides a powerful and flexible way to streamline your Eloquent queries, making it easier to manage and extend your application’s filtering capabilities.

Quick Look

class Product extends Model implements IsFilterable
{
    use Filterable;

    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL]),
        );
    }
}

$products = Product::filter([
    [
        'target' => 'name',
        'type'   => '$eq',
        'value'  => 'TV'
    ]
])->get();

Features

Field And Relationship Filter Example

class Product extends Model implements IsFilterable
{
    use Filterable;

    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL]),
            Filter::relation('manufacturer', [FilterType::HAS])->includeRelationFields()
        );
    }

    public function manufacturer(): HasOne
    {
        return $this->hasOne(Manufacturer::class);
    }
}

class Manufacturer extends Model implements IsFilterable
{
    use Filterable;

    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL])
        );
    }
}

$filters = [
    [
        'target' => 'name',
        'type'   => '$eq',
        'value'  => 'TV',
    ],
    [
        'type'   => '$has',
        'target' => 'manufacturer',
        'value'  => [
            [
                'type'   => '$eq',
                'target' => 'name',
                'value'  => 'Sony',
            ]
        ]
    ]
];

$sql = Product::filter($filters)->toRawSql();
SELECT *
FROM "products"
WHERE "products"."name" = 'TV'
  AND EXISTS (
    SELECT *
    FROM "manufacturers"
    WHERE "products"."manufacturer_id" = "manufacturers"."id"
      AND "manufacturers"."name" = 'Sony'
  )