How to Merge Eloquent Collections in Laravel?

Sovary February 3, 2023 867
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him