You can just fetch a normal collection from the modal, ie. Styles::all()
. Then use the groupBy
function on the collection.
// Sample data as per database query
$data = collect([
['style' => 'classy hat', 'color' => 'red'],
['style' => 'classy hat', 'color' => 'orange'],
['style' => 'classy hat', 'color' => 'green'],
['style' => 'stylish hat', 'color' => 'blue'],
['style' => 'stylish hat', 'color' => 'orange'],
]);
$styles = $data->groupBy('style');
foreach ($styles as $style => $colors) {
echo "<h1>" . $style . "</h1>";
echo implode(', ', $colors->pluck('color')->toArray());
}
That would give you
classy hat
red, orange, green
stylish hat
blue, orange
Alternatively you can build the whole array you need:
$styles = $data->groupBy('style')
->map(function ($styles) {
return $styles->pluck('color');
});
print_r($styles->toArray());
Array
(
[classy hat] => Array
(
[0] => red
[1] => orange
[2] => green
)
[stylish hat] => Array
(
[0] => blue
[1] => orange
)
Update to print
foreach ($styles->toArray() as $style => $colors) {
echo "<h1>" . $style . "</h1>";
echo implode(', ', $colors) . "<br />";
}
Update for blade view
@foreach ($styles->toArray() as $style => $colors)
<h1>{{ $style }}</h1>
@foreach ($colors as $color)
{{ $color }},
@endforeach
<!-- OR -->
{{ implode(', ', $colors) }}
@endforeach