Eloquent Filtering Package
Published on by Eric L. Barnes
The Eloquent Filtering package enhances the process of building dynamic query filters in Eloquent. Whether you’re managing large data sets or building complex search functionality, Eloquent Filtering helps streamline the experience.
What is Eloquent Filtering?
At its core, Eloquent Filtering allows developers to filter models dynamically based on incoming request data. Rather than manually chaining multiple query conditions, the package abstracts the process, enabling a more readable and maintainable codebase.
Basic Example
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();
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' )
Check out the official docs and see what’s new in V2 of the package.
Eric is the creator of Laravel News and has been covering Laravel since 2012.