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']);
 
$merged->all();

// ['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);

    dd($merge_collection->toArray());
    
    // ['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%]);
 
$merged->all();
 
// ['id' => 1, 'price' => 200, 'discount' => 10%]

 


You might also like:

Recommended Post
Featured Post
How to Send E-mail Using Queue in Laravel 7/8
How to Send E-mail Using Queue...

Today I will show you how to send e-mail using queue in laravel 7/8, many times we can see some processes take...

Read More

Oct-30-2020

How To Disable Weekends In jQuery Datepicker
How To Disable Weekends In jQu...

In this tutorial, we will see how to disable weekend dates in jquery datepicker. In the date picker, the weeke...

Read More

Jun-27-2022

Laravel 9 One To Many Polymorphic Relationship
Laravel 9 One To Many Polymorp...

In this article, we will see laravel 9 one to many polymorphic relationship. A one-to-many polymorphic relation is...

Read More

Apr-05-2022

How to Increase max_input_vars in PHP Ubuntu
How to Increase max_input_vars...

Hey folks! If you've ever encountered issues with PHP hitting the max_input_vars limit, you're not alone. In thi...

Read More

Feb-02-2024