4 months ago

Ordering results by relationship field without fetching all records

Posted 4 months ago by kovbo

Hello, I'm building an API using Laravel and facing a problem with ordering model results by a relationship field.

Let's imagine I have a User model, and a Profile model. Profile belongs to a User. Profile table has an 'age' field.

Can I order Users by the age field in Profile table and paginate result without fetching all Users from the database?

As for now, the only option I know is to use the raw query with join:

User::join('profiles', 'users.id', '=', 'profiles.user_id')

However, this option gives me an error because I have some appended accessors in my User model, invoked by $this->profile->age keywords.

I could also use ->get()->sortBy() function. But in this case pagination is not available, it will receive all records from the database.

Is there any way to order results by a relationship field using Eloquent?

Please sign in or create an account to participate in this conversation.