J'ai une collection à Laravel:
Collection {#450 ▼
#items: array:2 [▼
0 => Announcement {#533 ▶}
1 => Announcement {#553 ▶}
]
}
Ce sont les mêmes éléments. Comment supprimer l'un d'eux?
Le code complet est:
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;
}
$unique = $collection->unique();
$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'],
]);
Disons que vous voulez que la marque soit unique, dans ce cas, vous ne devriez avoir que deux marques "Apple" et "Samsung"
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
Ceci est tiré de https://laravel.com/docs/master/collections#method-unique