Laravel 5 Collections: Adding Values to a Collection With union

Laravel 5 Collections: Adding Values to a Collection With union

Laravel 5

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

public function union(
    $items
);

Example Use

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

$collection  = collect([
   'firstName' => 'Johnathon',
   'lastName'  => 'Koster',
   'age'       => 27
])->union([
  'firstName' => null,
   'lastName' => null,
   'age' => 18,
   'city' => 'Mayville'
]);

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

Start the Discussion

Leave a comment

Subscribe to our newsletter