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.

Signature

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

Example Use

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

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
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);
12});

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

1object(Illuminate\Support\Collection)
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