简体   繁体   中英

Laravel 8: How to list data on blade with foreach() loop

I want to show some data on blade by a foreach loop like this:

@foreach($topAnswered as $topAns)
    <tr>
        <td style="text-align:right;">
            <h3 class="h5 mb-0"><a href="{{ route('show.question', $topAns->slug) }}" class="text-uppercase">{{ $topAns->title }}</a></h3>
        </td>
        <td style="text-align:right;">
            <div>{{ $topAns->answers->count() }}</div>
        </td>
        <td style="text-align:right;">
            <div>{{ $topAns->likes->count() }}</div>
        </td>
    </tr>
@endforeach

But I need to retrieve these data descending based on $topAns->likes->count() . So how can I add this condition to the foreach() loop.

I would really appreciate if you share any idea or suggestion from you guys...

Thanks in advance.

You can use the method sortBy for collections, learn more here

@foreach($topAnswered->sortBy(function($answer, $key){return $answer->likes->count();}) as $topAns)
...
@endforeach

Some advices:

  • I think you should do this sorting on the controller, so in the blade file it is already sorted
  • On your controller you should eager load the likes so it doesn't make a new query for every likes relationship, ->with('likes')
  • You also can load ->withCount('likes') and sort by likes_count

learn more about relationships and eager loading here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM