Laravel Collection Public API: transform

November 30, 2016 —John Koster

transform(callable $callback)

The transform is identical to the map method, but instead of returning a new Collection instance, the transform method will modify the original collection instance. The transform method will return a reference to the original collection instance.

The following code example will demonstrate the usage of the transform method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// Modify the original and change the case of
11// each string to upper-case.
12$collection->transform(function($item, $key) {
13 return strtoupper($item);
14});

After the above code example has executed, the $collection variable would would contain a value similar to the following output:

1object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'FIRST' (length=5)
5 1 => string 'SECOND' (length=6)
6 2 => string 'THIRD' (length=5)

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.