Laravel collection class Illuminate\Support\Collection
provides multiple, convenient wrapper to work with arrays. We will discuss few of the collection methods in seperate articles.
In this article, we will show you how you can merge two collections with example. Laravel collection merge()
method merge any given array to first collection array.
If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance. The merge() method returns a new instance of collection and it doesn't change the original collection instance.
/**
* Show the index view
*
* @return void
*/
public function index()
{
$first = collect(['Foo']);
$second = collect([''Bar'']);
$merged = $first->merge($second);
dd($merged->toarray());
// ['Foo', 'Bar']
}
If a string key in the first collection matches a string key in the second collection, the first collection's value will overwrite the value in the second collection:
$first = collect(['id' => 1, 'rate' => 50]);
$second = $first->merge(['rate' => 80, 'total' => 100]);
$merged->all();
dd($merged->toarray());
// ['id' => 1, 'rate' => 80, 'total' => 100]
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Create Multiple Layouts for Different pages in Angular 12
Angular is open-source web application f...Laravel 5.5 - Yajra Datatable Example
Today, we are share with youu how to imp...Laravel Livewire CRUD Tutorial
Hello Artisan Today i am coming with...PHP explode and implode functions with example
Occasionally, you may have situation whe...How to Generate QR Code in Laravel 8
QR(Quick Response) code is a type of bar...