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.
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']
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']
}
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:
Hello developers! 👋 Ever found yourself dealing with a DataTable in Laravel and wished for a nifty way to filter th...
Feb-07-2024
Hello, laravel web developer! In this article, we'll see how to image upload in laravel 11 vue 3. Here, we'...
May-27-2024
Hey there! If you're diving into the world of PHP development on your Ubuntu 22.04 machine, you'll likely come a...
Jan-10-2024
In this article, we will see a laravel 9 vue js search example. Here, we will learn how to live search in laravel 9 usin...
Dec-14-2022