Ad

How Can I Make A Collection Unique?

- 1 answer

Here is my code:

$products = Products::orderBy('id')->get();

And here is my table:

// products
+----+----------+----------+
| id |  brand   |   name   |
+----+----------+----------+
| 1  | Cisco    | SF300-48 |
| 2  | Mikrotik | RB260GS  |
| 3  | Mikrotik | PoEhEX   |
+----+----------+----------+

Here is my code:

foreach($products as $product){
    echo $product->brand.PHP_EOL;
}

Current result:

/* Cisco
   Mikrotik 
   Mikrotik 

The expected result:

/* Cisco
   Mikrotik 

See? I need to make a laravel collection unique. array_unique() is for arrays and I cannot use it here. Any idea how can I do that?

Noted that I need to all names. (I mean I need these values SF300-48, RB260GS, PoEhEX). So I cannot use DISTINCT in the query either.

Ad

Answer

Use the unique() method:

$products->unique('brand')
Ad
source: stackoverflow.com
Ad