Laravel 5 Collections: Modifying Collection Elements With transform

April 22, 2018 —John Koster

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 behavior of both the transform and map functions can be thought as projecting the items in the collection into a new form; this can be useful for bridging method arguments for in compatible APIs, converting arrays to objects, etc.


1public function transform(
2 callable $callback

#Example Use

The following code example demonstrates the usage and behavior of the transform method:

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

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

2 protected 'items' =>
3 array
4 0 => string 'FIRST'
5 1 => string 'SECOND'
6 2 => string 'THIRD'

Some absolutely amazing

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.