Laravel Collection Get Unique Values Example

By Hardik Savani November 5, 2023 Category : Laravel

Here, I will show you how to works laravel collection get unique values. This tutorial will give you simple example of how to get unique values from array in laravel. I would like to share with you laravel collection unique values. I explained simply about laravel collection unique by column. you will do the following things for laravel collection unique case insensitive.

I will give you simple two example how to get unique value from laravel collection object and you can use it with laravel 6, laravel 7 and laravel 9 version.

let's see bellow examples:

Example 1:

Controller Code:

<?php

namespace App\Http\Controllers;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data = [1,2,4,5,3,2,2,4,5,6,8,9];

$data = collect($data)->unique();

dd($data);

}

}

Output:

Array

(

[0] => 1

[1] => 2

[2] => 4

[3] => 5

[4] => 3

[9] => 6

[10] => 8

[11] => 9

)

Example 2:

Controller Code:

<?php

namespace App\Http\Controllers;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data = collect( [

[

[ "id" => 1, "name" => "Hardik"],

[ "id" => 1, "name" => "Hardik"],

[ "id" => 2, "name" => "Mahesh"],

[ "id" => 3, "name" => "Rakesh"],

],

[

[ "id" => 1, "name" => "Hardik"],

[ "id" => 3, "name" => "Kiran"],

]

] );

$data = $data->map(function ($array) {

return collect($array)->unique('id')->all();

});

dd($data);

}

}

Output:

Array

(

[0] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

)

[2] => Array

(

[id] => 2

[name] => Mahesh

)

[3] => Array

(

[id] => 3

[name] => Rakesh

)

)

[1] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

)

[1] => Array

(

[id] => 3

[name] => Kiran

)

)

)

i hope it can help you...

Tags :
Shares