laravel tap method for collections

Laravel collections have a method named tap. With this method, we can do actions on the collection without changing it.

let’s see an example.

imagine we have a collection like this:

   $numbers = [12,9,5,4,6,3,1,25,8];
    $numbers_collection = collect($numbers);

we sort the collection and then use the tap method on the collection. in the closure inside tap, we dump the collection to see the results.

return $numbers_collection->sort()->tap(function ($collection){

the collection is sorted. now if we call the first() method on the collection we get the first item which is “1”:

  $output = $numbers_collection->sort()->tap(function ($collection) {

this time inside the tap method I reverse the collection then dump it and then dump the $output to see the first member of the collection.

 $output = $numbers_collection->sort()->tap(function ($collection) {


inside the tap closure, the collection is reversed so we expect the first item to be “25” but it is still “1”. That’s because tap does not change the original collection. it creates a copy of that. this is useful when you want to do some operation on a particular part of the collection without having to change the collection itself.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *