Laravel 5 Collections: Execute a Callback on the Collection Instance While Returning the Original Collection Instance With tap

April 22, 2018 —John Koster

The tap method will allow you supply a callback that will receive a copy of the current collection instance. The user supplied function will not modify the original collection, but will return a reference the original collection.

#Signature

1public function tap(
2 callable $callback
3);

#Example Use

In the following example, we will tap into a collection's items, perform some action on them, and return an array containing the original collection's items.

1// Create a new collection.
2$collection = collect([
3 'Alice',
4 'Bob',
5 'Charlie'
6]);
7 
8$items = $collection->tap(function ($col) {
9 // We now have access to a copy of
10 // the original collection instance.
11 $col->map(function ($name) {
12 // This will not change the original collection.
13 return mb_strtoupper($name);
14 });
15})->toArray();

After the above code has executed, the $items array will contain the same elements stored within the original collection instance; they will not have been converted to their upper-cased variant.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.