Search code examples
laravelforeacheloquentlaravel-bladelaravel-query-builder

Unable to Sort data in dual foreach loop in Laravel


I am fetching data of User with the Subject model and Review model. There is a rating column in the Review of the related User. What I am trying to do is fetch the highest rating first but failed.

Heres my Controller:

function guest()
{
    $topTutors = User::where('type', 'tutor')->with('subject')->with('review')->get();     

    return view('welcome', compact('topTutors'));
}
@foreach($topTutor->review as $singleReview)
    <div class="star-rating" data-rating="{{ $singleReview->rating }}"></div>
@endforeach

Here's the Blade where I wasn't able to sort Data I used sortbyDesc but It's not working:


Solution

  • Try this to sort your users based on their review rating:

    $topTutors = User::where('type', 'tutor')
        ->with('subject', 'review')
        ->get()
        ->sortbyDesc(function($user) {
            return $user->review->max('rating');
        });