Laravel Pipeline Query Collection

Packages

June 7th, 2022

laravel-query-pipelines.png

The Laravel Pipeline Query Collection package contains a collection of Eloquent query filters for pipelines. Given a complex query of filters, the code can get a bit unwieldy around query conditions:

1$users = User::query()
2 ->when($request->name ?? null, function($query, $name) {
3 $query->where('name', 'like', "%$name%");
4 })
5 ->when($request->is_admin ?? null, function($query, $isAdmin) {
6 $query->where('is_admin', $isAdmin ? 1 : 0);
7 })
8 ->when($request->created_at_from ?? null, function($query, $date) {
9 $query->where('created_at', '>=', $date);
10 })
11 ->when($request->created_at_to ?? null, function($query, $date) {
12 $query->where('created_at', '<=', $date);
13 })
14 ->get();

Using this package could be written as follows:

1use Baro\PipelineQueryCollection;
2 
3// users?name=Baro&is_admin=1&created_at_from=2022-06-01&created_at_to=2022-06-31
4$users = Users::query()->filter([
5 new PipelineQueryCollection\RelativeFilter('name'),
6 new PipelineQueryCollection\BooleanFilter('is_admin'),
7 new PipelineQueryCollection\DateFromFilter('created_at'),
8 new PipelineQueryCollection\DateToFilter('created_at'),
9])
10->get();

At the time of writing, this package contains the following filters:

  • Bitwise
  • Boolean
  • Date from
  • Date to
  • Exact
  • Relation
  • Relative
  • Scope
  • Sort

You can get started with this package on GitHub at l3aro/pipeline-query-collection. The package's author also wrote a more in-depth article—Building a sexy query filter—which walks you through the idea behind the package.

Filed in:

Paul Redmond

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

Laravel News Partners