How to Merge Unique Values of a Collection in Laravel?

Nov 21, 2022 . Admin

Hello Friends,

This tutorial is focused on how to merge the unique values of a collection in laravel. let’s discuss about how to merge unique values into the collection in laravel. We will look at an example of a laravel collection merging unique values. This post will give you a simple example of laravel merging unique values into the collection. Here, Creating a basic example of a laravel collection merges unique values examples.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Format Route web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MergeUniqueController;

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

Route::get('/index',[MergeUniqueController::class, 'index']);
Step 3: create MergeUniqueController

we will create MergeUniqueController. so you can see the below code with output:

php artisan make:controller MergeUniqueController

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MergeUniqueController extends Controller
     * The attributes that are mass assignable.
     * @var array
    public function index()
        $firstCollection = collect(['One', 'Two', 'Three']);

        $secondCollection = collect(['Three', 'Four', 'Five']);

        $mergedCollection = $firstCollection->merge($secondCollection);

        $mergedCollection = $mergedCollection->unique(function ($item) {

                            return $item;



Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

#items: array:5 [▼
    0 => "One"
    1 => "Two"
    2 => "Three"
    4 => "Four"
    5 => "Five"

I hope it can help you...