Eloquent Filtering
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
Large Filter Library
Many core filter methods.
Field Filters
Filter your models fields.
Relationship Filters
Filter by relationship existence.
Pivot Filters
Filter your intermediate table.
Required Filters
Set filters as required.
Validation
Add validation to your defined filters.
Custom Filters
Create your own custom filters.
Alias
Alias fields and relationships.
Filter JSON Columns
Json path wildcard support.
Granular Control
Specify filter types.
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'
)