Laravel Collection Get Unique Values Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection Sum Column Example
- How to Get Specific Attributes from Laravel Collection?
- Laravel Collection Check Contains Value Example
- Laravel Collection keys() Method Example
- Laravel Collection isEmpty() and isNotEmpty() Method Example
- Laravel Collection intersect() and intersectByKeys() Method Example
- Laravel Collection Map Method Example
- Laravel Collection SortByDesc Tutorial with Examples
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example