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; }
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.
$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'], ]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With