Ad
How Can I Make A Collection Unique?
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad