Laravel 5 Collections: Modifying Collection Elements With transform

1 min read

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'

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch