Laravel 5

Laravel 5 Collections: Merging Multiple Collection Values With merge


John Koster

Published on April 22, 2018

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.


1public function merge(
2 $items

Example Use

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

2 protected 'items' =>
3 array
4 0 => string 'first'
5 1 => string 'second'
6 2 => string 'third'
7 3 => string 'fourth'

Explore The Blog

Laravel 5: Message Bags

Published on April 21, 2018

Read More

Laravel Collection Public API: all

Published on November 29, 2016

Read More

Laravel Array Helper Function: array_build

Published on November 18, 2016

Read More