How to merge two Collections in Laravel?

10-Mar-2023

.

Admin

Hi Guys,

In this example, i will explain how you can two collections merge example. i will show collections in merge method. we are two collections merge using merege method.

The merge methods merges the given first collection with the second collection in the collection. The merge method will replace any first collection in the original second collection's items if a string key with the same value exists in the supplied $items.

If the first collection keys are numeric, the second collection will be added to the end of the new collection's. The merge method can accept either an array or a Collection instance. The merge method returns a new instance of Collection and does not modify the original collection instance.

Here the example of marge method

Example 1


here the example $old collection and $new collection merge

/**

* Show the application dashboard.

*

* @return \Illuminate\Contracts\Support\Renderable

*/

public function index(){

$old = collect(['buysycle']);

$new = collect(['car']);

$merged = $old->merge($new);

dd($merged->toarray());

}

After the above code has executed, the $merged variable will be an instance of Collection and contain a value similar to the following output:

output

array:2 [?

0 => "buysycle"

1 => "car"

]

Example 2

here the example $uses collection and $admins collection merge

/**

* Show the application dashboard.

*

* @return \Illuminate\Contracts\Support\Renderable

*/

public function index(){

$users = User::get();

$admins = Admin::get();

$mergedAdminUser = $admins->merge($users);

dd($merged->toarray());

}

After the above code has executed, the $mergedAdminUser variable will be an instance of Collection and contain a value similar to the following output:

output

array:3 [?

0 => array:6 [?

"id" => 6

"name" => "admin"

"email" => "admin@gmail.com"

"email_verified_at" => null

"created_at" => "2020-01-03 10:58:39"

"updated_at" => "2020-01-03 10:58:39"

]

1 => array:6 [?

"id" => 7

"name" => "Akeem Stanton"

"email" => "kaitlyn88@example.com"

"email_verified_at" => "2020-01-11 11:31:19"

"created_at" => "2020-01-11 11:31:19"

"updated_at" => "2020-01-11 11:31:19"

]

2 => array:6 [?

"id" => 10

"name" => "Kayla Sanford"

"email" => "antonia.gorczany@example.com"

"email_verified_at" => "2020-01-11 11:31:19"

"created_at" => "2020-01-11 11:31:19"

"updated_at" => "2020-01-11 11:31:19"

]

]

It will help you...

#Laravel 7

#Laravel

#Laravel 6