How to Merge two Collections in Laravel

  76578 views   8 months ago Laravel

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]