Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates in collection?

I have collection in Laravel:

Collection {#450 ▼   #items: array:2 [▼     0 => Announcement {#533 ▶}     1 => Announcement {#553 ▶}   ] } 

It is the same items. How ti delete one of them?

Full code is:

public function announcements()     {          $announcements = $this->categories_ann->map(function ($c) {             return $c->announcements->map(function ($a) {                 $a->subsribed = true;                  return $a;             });         });          $flattened = $announcements->groupBy("id")->flatten();          return $flattened;     } 
like image 386
Blablacar Avatar asked May 24 '17 22:05

Blablacar


People also ask

Which collection is used to remove duplicate values?

As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.


2 Answers

$unique = $collection->unique(); 
like image 173
MevlütÖzdemir Avatar answered Sep 22 '22 09:09

MevlütÖzdemir


$collection = 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'], ]); 

Then let's say you want the brand to be unique, in this case you should only get two brands 'Apple', and 'Samsung'

$unique = $collection->unique('brand');  $unique->values()->all(); /*     [         ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],         ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],     ] */ 

This is taken from https://laravel.com/docs/master/collections#method-unique

like image 21
Richard Avatar answered Sep 23 '22 09:09

Richard