Maxwell
Maxwell

Reputation: 151

Looping through collections -Laravel

I was trying to loop through a collection based on the keyenter image description here

What I am trying to accomplish here is to group each company based on the alphabet in my view.

How do I loop through this??

$results = $companies->sortBy('name')->groupBy(function ($item, $key) {
                 return substr($item['name'], 0, 1);
        });

       dump($results);

Controller

Upvotes: 6

Views: 44402

Answers (2)

Rwd
Rwd

Reputation: 35180

As an alternative to @msonowal's answer you can also use each():

$results->each(function ($collection, $alphabet) {
    dump($alphabet, $collection);
});

However, if you're going to loop through them in a blade file you would use:

@foreach ($results as $alphabet => $collection)
    {!! dump($alphabet, $collection) !!}
@endforeach

https://laravel.com/docs/master/blade#loops

Upvotes: 17

msonowal
msonowal

Reputation: 1687

foreach($results as $alphabet => $collection) {
  dump($alphabet, $collection);
}

Upvotes: 3

Related Questions