Hello Devs 

In this tutorial, we will learn How to merge two Collections in Laravel?

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.

Follow this step by step guide below. 




Example 1

 /**
 * 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());
}
 


output

 array:2 [?

  0 => "buysycle"

  1 => "car"

]

 



Example 2

/**
 * 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());
}
 


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"

  ]

]

 


May this example help you.