How To Merge Two Collections In Laravel

Websolutionstuff | Jul-18-2022 | Categories : Laravel

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.

Example 1: Merge multiple collections laravel

If the given items's keys are numeric, the values will be appended to the end of the collection.

$collection = collect(['laravel', 'php']);
$merged = $collection->merge(['jquery', 'javascript']);

// ['laravel', 'php', 'jquery', 'javascript']


Example 2: Merge collections with toArray() function

This method is recursive, so all attributes and all relations will be converted to arrays.

public function index()
    $collection_1 = collect(['collection 1']);

    $collection_2 = collect(['collection 2']);

    $merge_collection = $collection_1->merge($collection_2);

    // ['collection 1', 'collection 2']



Example 3: Merge key and value collections

 If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection.

$collection = collect(['id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => 10%]);
// ['id' => 1, 'price' => 200, 'discount' => 10%]


You might also like:

Recommended Post
Featured Post
Laravel 11 Livewire Toastr Notification
Laravel 11 Livewire Toastr Not...

Hello, laravel web developers! In this article, we'll see how to add toastr notification in livewire laravel 11. Her...

Read More


Laravel 8 Many To Many Relationship Example
Laravel 8 Many To Many Relatio...

In this example we will see laravel 8 many to many relationship example. Use many to many relationship in lara...

Read More


How to Install PHP PDO MySQL Extension in Ubuntu 22.04
How to Install PHP PDO MySQL E...

Hey there! If you're diving into PHP development on Ubuntu 22.04 and need to connect your applications to MySQL data...

Read More


Create Dummy Data Using Laravel Tinker
Create Dummy Data Using Larave...

In this example we can see how to add multiple dummy records in the database at a time using tinker and factory, mo...

Read More