How to Merge Eloquent Collections in Laravel?

Sovary February 3, 2023 645
1 minute read

In this article, we will see how to merge two collections in laravel 8 or laravel 9. The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. In this example, we will merge two collections using the laravel merge() method. The merge method merges the given array or collection with the original collection.

So, let's see laravel 8/9 merge two collections, laravel collection merge by key, how to merge collections in laravel, laravel collection merge.

This article will help you to merge multiple collections in Laravel. We will explain how to merge two collections into one collection with simply methods below.

Example #1 - Using Collection Merge

This code below you can paste in controller file.

<?php
  
namespace App\Http\Controllers;
   
class HomeController extends Controller
{

    public function index()
    {
       $fruit = collect(['banana']);
       $vihecle= collect(['car','motor' ]);
       $merged = $fruit->merge($vihecle);

       dd($merged->toarray());
    }
 
}

Output

array:3 [▼
  0 => "banana"
  1 => "car"
  2 => "motor"
]

Example #2 - Using Merge Model Data

This controller required two models, but we are not going to show how to create those models.

<?php
  
namespace App\Http\Controllers;
use App\Models\Student;
use App\Models\Teacher;
   
class HomeController extends Controller
{

    public function index()
    {
       $students = Student::get();
       $teachers = Teacher::get();
       $merged = $students->merge($teachers);

       dd($merged->toarray());
    }
 
}

After run the above code you will see similar output as below.

Output

array:2 [▼
  0 => array:6 [▼
    "id" => 12
    "name" => "student 1"
    "email" => "test1@gmail.com"
    "email_verified_at" => null
    "created_at" => "2022-01-16 10:58:39"
    "updated_at" => "2022-01-20 7:51:25"
  ]

  1 => array:6 [▼
    "id" => 73
    "name" => "teacher 1"
    "email" => "test2@example.com"
    "email_verified_at" => null
    "created_at" => "2022-01-11 6:31:19"
    "updated_at" => "2022-01-21 8:21:55"
  ]
]

Hope you found this short article help you. Have a nice day!

You might Also Like:

Laravel  PHP  Laravel Collections 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him