Laravel “Pipe Through” Collections Method

News

January 12th, 2022

collections-pipethrough-featured.png

Laravel v8.78.1 introduces a new pipeThrough() collection method, allowing developers to insert an array of pipe callbacks that can manipulate the collection:

Recently merged into Laravel, you will soon be able to call collect()->pipeThrough($pipes) to run a collection through an array of callbacks, passing return values into following pipes 🤩 pic.twitter.com/5m9fThcoaw

— Steve Bauman (@SteveTheBauman) January 5, 2022

The author of the pull request, Steve Bauman, shared an additional example that might help you visualize example use-cases of this method:

1$process = [
2 // Iterate through the health checks and attempt,
3 // filtering the collection by unsuccessful.
4 fn ($checks) => $checks->filter(
5 fn ($check) => ! $check->attempt()
6 ),
7 
8 // Iterate through all the unsuccessful checks
9 // notifying their users of each failed check.
10 fn ($unsuccessful) => $unsuccessful->each(
11 fn ($check) => $check->users()->each(
12 fn ($user) => $user->notify(
13 new HealthCheckFailed($check)
14 )
15 )
16 )
17];
18 
19collect(HealthChecks::all())->pipeThrough($process);

The pipeThrough() method is a flexible way to run whatever collection code you have through a series of callbacks and invokable classes. Yet, the implementation is simple. Here’s the pipeThrough method in the Collection class at the time of release:

1public function pipeThrough($pipes)
2{
3 return static::make($pipes)->reduce(
4 function ($carry, $pipe) {
5 return $pipe($carry);
6 },
7 $this,
8 );
9}

A related method in the Collection class is the pipe() method, which accepts a single callable and returns the result of the executed closure.

1$collection = collect([1, 2, 3]);
2 
3$piped = $collection->pipe(function ($collection) {
4 return $collection->sum();
5});

If you’d like to learn more about the pipeThrough method, check out Pull Request #40253. Also, you can see the complete list of changes between 8.78.0 and this week's 8.78.1 release on GitHub.

Filed in:

Paul Redmond

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

Laravel News Partners