Laravel collection merge two collections

Laravel collection class Illuminate\Support\Collection provides multiple, convenient wrapper to work with arrays. We will discuss few of the collection methods in seperate articles.

In this article, we will show you how you can merge two collections with example. Laravel collection merge() method merge any given array to first collection array.

If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance. The merge() method returns a new instance of collection and it doesn't change the original collection instance.

Example:

 /**
 * Show the index view
 *
 * @return void
 */
public function index()
{
    $first = collect(['Foo']);

    $second = collect([''Bar'']);

    $merged = $first->merge($second);

    dd($merged->toarray());
    // ['Foo', 'Bar']
}

If a string key in the first collection matches a string key in the second collection, the first collection's value will overwrite the value in the second collection:

Example:

$first = collect(['id' => 1, 'rate' => 50]);

$second = $first->merge(['rate' => 80, 'total' => 100]);

$merged->all();

dd($merged->toarray());
// ['id' => 1, 'rate' => 80, 'total' => 100]

I hope it will help you.