Title of the topic is clearly not relevant to the question, because I lack the erudition to formulate the question, but the essence is as follows:

There is a table of cities, when receiving the collection, sorting alphabetically is used, sortBy ('name') , when outputting via @foreach () you need to get the first letter of sorted cities. For example:

enter image description here

Is there a way in Laravel to do this? Or do you need to write a filter with pens?

    1 answer 1

    Grouping by the first letter of the name can be done like this:

    $cities = City::sortBy('name') ->get() ->groupBy(function($item) { return mb_substr($item->name, 0, 1); }); 

    In the template output as follows:

     @foreach($cities as $letter => $letterCities) <h3>{{ $letter }}</h3> @foreach($letterCities as $city) <p>{{ $city->name }}</p> @endforeach @endforeach