1

I've read a lot about this on internet, but it seams like it is a different problem. So ... what I have is:

$students = User::with('user_profile')
             ->whereHas('roles', function($query){
                 return $query->where('slug', 'student');
             })->get()
             ->sortBy(function($user){
                 return $user->user_profile->country;
             });

Yes this would work to sort students by their country, but if they have same country, the second field I want to sort is their first name, so I tried this:

$students = User::with('user_profile')
                 ->whereHas('roles', function($query){
                     return $query->where('slug', 'student');
                 })->get()
                 ->sortBy(function($user){
                     return $user->user_profile->country;
                 })
                 ->sortBy(function($user){
                     return $user->user_profile->first_name;
                 });

Then tried to change the country, and now, it can only sort the first name and not the country (which is my priority field to sort before the first name).

BTW, I'm using Laravel 5.1

Cheers!

Blues Clues
  • 1,694
  • 3
  • 31
  • 72

1 Answers1

-1

It is a bit counter-intuitive, but when you are chaining sortBy in Eloquent, they are applied in reverse. So your example code actually says "Sort by first name and then by country".

Other possible solution will be to concatenate both fields you want to sort on:

$students = User::with('user_profile')
             ->whereHas('roles', function($query){
                 return $query->where('slug', 'student');
             })->get()
             ->sortBy(function($user){
                 return $user->user_profile->country . "-". $user->user_profile->first_name;
             })
Daniel Alexandrov
  • 1,299
  • 8
  • 13