1

Trying to think of alternate ways to get what I need from my API.

I am using Laravel Spark and have a query along the lines of:

$team = Team::with('users')->find($id);

The users relationship on the Team model is:

public function users()
{
   return $this->belongsToMany(
       'App\User', 'team_users', 'team_id', 'user_id'
   )->withPivot('role')->orderBy('current_active_team', 'DESC');
}

I am currently ordering this by a field on the users table, but I also want to order by a method on the Users model:

public function queueLength()
{
    // returns an integer for the users queue length
}

To return this data I am currently adding this under my query:

foreach ($team->users as $user) {
    $user->queueLength = $user->queueLength();
}

Is there a way I can order the $team->users by their queueLength?

Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • Add the queue length as an attribute to your model? [See this question](https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load) – milo526 Aug 01 '17 at 13:36
  • How the queueLength is? If it comes from other database table, you can do a join to allow ordering by it. – Elias Soares Aug 01 '17 at 14:00

1 Answers1

0

One solution will be use collection sortBy.

First make queueLength as an attribute.

public function getQueueLengthAttribute()
{
    // returns an integer for the users queue length
}

Then use collection sortBy

$team->users->sortBy('queueLength');

PS: this will not be a good idea if you have huge amount of data or using pagination.

Jithin Jose
  • 1,761
  • 2
  • 19
  • 35