dvanced 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): Builder14 {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.
0 comments:
Post a Comment
Thanks