Advanced Eloquent Model Filters

Packages

October 6th, 2021

20-eloquent-tricks.png

Advanced Laravel Model Filters is a package that gives you fine-grained control and reusable classes you can use to filter Eloquent models. The readme has an example where perhaps you'd like to filter by the name column:

1$filters = EloquentFilters::make([
2 new NameFilter($request->name)
3]);
4 
5$products = Product::filter($filters)->get();

The NameFilter class is a reusable filter you can reuse wherever you need to filter by name:

1use Pricecurrent\LaravelEloquentFilters\AbstractEloquentFilter;
2use Illuminate\Database\Eloquent\Builder;
3 
4class NameFilter extends AbstractEloquentFilter
5{
6 protected $name;
7 
8 public function __construct($name)
9 {
10 $this->name = $name;
11 }
12 
13 public function apply(Builder $builder): Builder
14 {
15 return $query->where('name', 'like', "{$this->name}%");
16 }
17}

The NameFilter is now reusable, as shown in the following example being used in tandem with the User model. This code example also demonstrates how you can chain methods on filter() as if it was an Eloquent builder instance:

1$filters = EloquentFilters::make([
2 new NameFilter($request->user_name)
3]);
4 
5$products = User::query()
6 ->filter($filters)
7 ->limit(10)
8 ->latest()
9 ->get();

You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.