0

I have a custom attribute on my User model that's calculates the length of some other tables and returns an integer value:

public function GetCurrentQueueLengthAttribute()
{
    // return int
}

I then have an API endpoint that returns a "Team" with all its users (simple Spark pivot)

public function show($teamId)
{
    $query = Team::query();
    $query->with('users')->where('id', $teamId);
    $team = $query->first();

    return $team->users->sortBy('currentQueueLength');

    return $team;
}

The issue is that the returned data doesn't change order. There are no errors, just the same order of the users every time.

Is there something I'm missing?

Lovelock
  • 7,689
  • 19
  • 86
  • 186

1 Answers1

0

The sortBy function is not to be mistaken by the orderBy function, the first one sorts a collection, the second one alters the sql of the query builder.

To be able to use the sortBy function one first needs to retrieve the collection. These functions can still be chained by using:

return $team->users()->sortBy('currentQueueLength');

optionally one could also use orderByRaw if you are willing to write a custom sql query for the sorting.

milo526
  • 5,012
  • 5
  • 41
  • 60
  • I don't think that will work because we don't want to sort on the database since this is a custom attribute. The database has no idea about `currentQueueLength`. We'd want to grab the collection first and sort that using PHP. – user1669496 Aug 01 '17 at 14:40