Laravel 5 Collections: Adding Values to a Collection With union

April 22, 2018 —John Koster

The union method will add the $items value to a copy of the existing collection. If there are key collisions between the collection instance and the provided $items, the elements from the collection instance will be used instead.

The union method does not modify the collection instance it was invoked on; instead, it will return a copy of the original collection with the provided $items added to it.

#Signature

1public function union(
2 $items
3);

#Example Use

The following example demonstrates both the basic use of the union method as well as its behavior when it encounters conflicting keys:

1$collection = collect([
2 'firstName' => 'Johnathon',
3 'lastName' => 'Koster',
4 'age' => 27
5])->union([
6 'firstName' => null,
7 'lastName' => null,
8 'age' => 18,
9 'city' => 'Mayville'
10]);

After the above code has executed, the $collection collection instance would contain the following values:

Key Value
firstName Johnathon
lastName Koster
age 27
city Mayville

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.