Laravel collection merge example

In this post, we will explore the Laravel collection merge method with clear examples. You will learn how to merge collections by value and combine Eloquent collections in Laravel.

Laravel collections simplify data handling, making your tasks more efficient. They offer powerful methods to process, transform, and merge data effortlessly.

How to merge laravel collections?

The Laravel collection merge method allows you to combine two or more collections seamlessly. This method is especially useful for managing and organizing data efficiently in your Laravel application.

In this post, we will look at multiple examples of merging collections to help you understand and use this method effectively.

Let’s See the Examples Below:
  1. Example 1: Simple Example of Laravel Collection Merge
  2. Example 2: Laravel collection merge unique​
  3. Example 3: Laravel eloquent merge collection
Example 1: Simple Example of Laravel Collection Merge
public function index() 
{
    $firstArrayCollection = collect(['One', 'Two', 'Three']);
    $secondArrayCollection = collect(['Four', 'Five', 'Six']);
    $mergedArrayCollection = $firstArrayCollection->merge($secondArrayCollection);
    $mergedArrayCollection->all();
    
    dd($mergedArrayCollection);
}
Example 2: Laravel collection merge unique
 public function index()
    {
        $firstArrayCollection = collect(['One', 'Two', 'Three']);
        $secondArrayCollection = collect(['Three', 'Four', 'Five']);
        
        $mergedArrayCollection = $firstArrayCollection->merge($secondArrayCollection)->unique();

        dd($mergedArrayCollection->all());
    }
Example 3: Laravel eloquent merge collection
public function index()
    {
        $firstArrayCollection = Post::get();
        $secondArrayCollection = User::get();

        $mergedArrayCollection = $firstArrayCollection->merge($secondArrayCollection);

        $mergedArrayCollection->all();
    }
Example 4: Merging and filtering data

Use merge() and filter() to merging two collections and filter the data based on a condition.

    public function index()
    {
        $basicData = collect([
            ['id' => 1, 'title' => 'First title'],
            ['id' => 2, 'title' => 'Second title'],
            ['id' => 3, 'title' => 'Third title'],
        ]);

        $data = collect([
            ['id' => 1, 'status' => 1],
            ['id' => 2, 'status' => 0],
            ['id' => 3, 'status' => 1],
        ]);

        $mergedData = $basicData->map(function ($item) use ($data) {
            return $extraData = $item + $data->firstWhere('id', $item['id']);
        })->filter(function ($item) {
            return $item['status'] == 1;
        });

        dd($mergedData);
    }

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *