How to Remove Duplicate Rows In Laravel Collection ?

Laravel 8 , Laravel 7 , Laravel , Laravel 6

Nicesnippets

1446

04-06-2021


Hi Guys,

In this example,I will learn you how to remove duplicates from collection laravel.you can easy and simply remove duplicates from collection laravel.

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys and value.

Let's see bellow one by one example with output:

Example 1:


/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myCollection = collect(['a','b','b','c','d','e']);

$uniqueCollection = $myCollection->unique();

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection {#276 ?

#items: array:5 [?

0 => "a"

1 => "b"

3 => "c"

4 => "d"

5 => "e"

]

}

Example 2:

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myCollection = collect([

['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],

['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],

['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],

['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],

['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],

]);

$uniqueCollection = $myCollection->unique('type');

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection {#276 ?

#items: array:2 [?

0 => array:3 [?

"name" => "iPhone 6"

"brand" => "Apple"

"type" => "phone"

]

2 => array:3 [?

"name" => "Apple Watch"

"brand" => "Apple"

"type" => "watch"

]

]

}

Example 3:

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myCollection = collect([

['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],

['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],

['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],

['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],

['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],

]);

$uniqueCollection = $myCollection->unique(function ($item) {

return $item['brand'].$item['type'];

});

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection {#276 ?

#items: array:4 [?

0 => array:3 [?

"name" => "iPhone 6"

"brand" => "Apple"

"type" => "phone"

]

2 => array:3 [?

"name" => "Apple Watch"

"brand" => "Apple"

"type" => "watch"

]

3 => array:3 [?

"name" => "Galaxy S6"

"brand" => "Samsung"

"type" => "phone"

]

4 => array:3 [?

"name" => "Galaxy Gear"

"brand" => "Samsung"

"type" => "watch"

]

]

}

It will help you...