Search

Laravel 5 Collections: Merging Multiple Collection Values With merge

April 22, 2018 —John Koster

The merge methods merges the given $items with the items in the collection. The merge method will replace any item in the original collection's items if a string key with the same value exists in the supplied $items. If the $items keys are numeric, the new $items will be added to the end of the new collection's items. The merge method can accept either an array or a Collection instance. The merge method returns a new instance of Collection and does not modify the original collection instance.

The behavior of the merge method is similar to PHP's array_merge function.

#Signature

1public function merge(
2 $items
3);

#Example Use

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// Merge an array with the existing collection.
9$newCollection = $collection->merge(['fourth']);

After the above code has executed, the $newCollection variable will be an instance of Collection and 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'
7 3 => string 'fourth'

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.