How to merge two collections in Laravel

Laravel has rich collections by which you can modify and use laravel collections. In this article, we will use merge() method and show how you can merge two collections into one.

The merge() method merges given array or collection into original collection.

Suppose you have cars and bikes table, and you want to merge them, then you can do it something like this:

<?php

use App\Models\Car;
use App\Models\Bike;

/**
 * Show the vehicles view.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
    $cars = Car::get();
    
    $bikes = Bike::get();

    $vehicles = $cars->merge($bikes);
}

Same way you can merge two array into single array.

<?php

$cars = collect(['Chevrolet', 'Tesla']);

$cars_2 = collect(['GM']);

$new_cars = $cars->merge($cars_2); // ['Chevrolet', 'Tesla', 'GM']

Note that if string key in given array matches with original array, then it will replace with the original array.

<?php

$product_1 = collect(['product_id' => 1, 'price' => 80]);

$product_2 = collect(['price' => 100, 'size' => 'xl']);

$new_cars = $product_1->merge($product_2);

// ['product_id' => 1, 'price' => 100, 'size' => 'xl']

I hope you liked the article and help in your work.

Tags: