To merge two collections in Laravel, you can use the merge
method on the first collection. The merge
method will add the items from the second collection to the first collection and return a new collection with the merged items.
Here’s an example:
$collection1 = collect([1, 2, 3]);
$collection2 = collect([4, 5, 6]);
$merged = $collection1->merge($collection2);
// $merged is a new collection containing [1, 2, 3, 4, 5, 6]
You can also pass an array or an iterable object as the argument to the merge
method.
If you want to merge the collections and preserve the keys, you can use the union
method instead. This method will create a new collection with the items from both collections, using the keys from the first collection for all items.
$collection1 = collect(['a' => 1, 'b' => 2]);
$collection2 = collect(['c' => 3, 'd' => 4]);
$merged = $collection1->union($collection2);
// $merged is a new collection containing ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]
Note that both the merge
and union
methods return a new collection, they do not modify the original collections. If you want to update the original collection with the merged items, you can use the push
or put
methods.
$collection1 = collect([1, 2, 3]);
$collection2 = collect([4, 5, 6]);
$collection1->push($collection2->all());
// $collection1 is now [1, 2, 3, 4, 5, 6]
$collection1 = collect(['a' => 1, 'b' => 2]);
$collection2 = collect(['c' => 3, 'd' => 4]);
$collection1->put($collection2->keys()->all(), $collection2->values()->all());
// $collection1 is now ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]