In my controller I am passing to a view a bunch of categories in alphabetical order like this :
public function index()
{
$categories = Category::orderBy('name', 'asc')->get();
return view('categories')->with('categories',$categories);
}
In my view, I want to display in separate columns corresponding to letters from the alphabet each of these categories, so in column "A" I will have all categories starting with A and so on.
Is it possible to filter the results in the view by letter in order to achieve this, and if yes, how can it be done?
You can group the list of categories by first letter in your controller and then pass the result to your view, here is how to do:
Controller:
public function index() {
$categories = Category::orderBy('name', 'asc')->get();
$groups = $categories->reduce(function ($carry, $category) {
// get first letter
$first_letter = $category['name'][0];
if ( !isset($carry[$first_letter]) ) {
$carry[$first_letter] = [];
}
$carry[$first_letter][] = $category;
return $carry;
}, []);
return view('categories')->with('groups', $groups);
}
View:
@foreach($groups as $letter => $group)
<ul>
<li>{{ $letter }}</li>
@foreach($group as $category)
<li>{{ $category['name'] }}</li>
@endforeach
</ul>
@endforeach
Here is a working example using array_reduce (it's the same as Collection::reduce function above)
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