kovbo's avatar
Level 1

Order by relations field

I want to order results by relations and apply pagination.

Let's say we need to order users by their role in the profiles table

To do so, you have to join the profiles table:

User::join('profiles', 'users.id', '=', 'profiles.user_id')
  ->orderBy('role')
  ->paginate(10);

It works, but it always gives random results. For example, If I have 100 users with identical role, this query will return 10 random users for the first page, 10 random for the second page and so on. The second page may contain users from the first page making pagination pointless.

How to avoid this behaviour and make proper pagination?

0 likes
2 replies
MichalOravec's avatar
Level 75

Add another orderBy which is everytime in the same order, for example id

User::select('users.*')->join('profiles', 'users.id', '=', 'profiles.user_id')
  ->orderBy('profiles.role')
  ->orderBy('users.id')
  ->paginate(10);
1 like
kovbo's avatar
Level 1

Wow, it really worked! You are amazing!

Please or to participate in this conversation.