@rediska Try:
// ...
$colors = $products->pluck('colors.id', 'colors.title')
->filter(function($value, $key) {
return $value != '[]';
})->unique();
//...
It seems I wrote nonsense in the question)) But I will try to explain in more detail. Implemented in laravel. I need to get all available "color" attributes from a collection of products. I do like this (many-to-many relationship through an intermediate table):
$colors = $products->pluck('colors')
->filter(function($value, $key) {
return $value != '[]';
})
->unique();
But that doesn't work. Because in this case, unique is applied to the first nested collections (otherwise the products themselves), and each product has its own nested collection of the "color" attribute.
That is, if you call dd($products), then I get this (Excess removed for readability):
Illuminate\Pagination\LengthAwarePaginator {#1594 ▼
#total: 7
#items: Illuminate\Database\Eloquent\Collection {#1814 ▼
#items: array:7 [▼
0 => App\Models\Product {#1681 ▼
#fillable: array:17 [▶]
...
#attributes: array:20 [▶]
...
#relations: array:9 [▼
"colors" => Illuminate\Database\Eloquent\Collection {#1760 ▼
#items: array:2 [▼
0 => App\Models\Color {#1782 ▼
...
#attributes: array:12 [▼
"id" => 1
"title" => "blue"
]
...
1 => App\Models\Color {#1778 ▼
...
#attributes: array:12 [▼
"id" => 3
"title" => "red"
]
...
1 => App\Models\Product {#1649 ▶}
...
Each item has a color. Some have it, some have not, some have several. I need to get unique colors (with id and title) without repetition.
How can I implement this correctly?
Please or to participate in this conversation.