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:
->with('likes')
->withCount('likes')
and sort by likes_count
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.