Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yassinebneghr's avatar

SortBy not working with pivot column as sorting criteria

i am trying to sort using a pivot column as a sorting criteria

public function sortByScore()
    {
        return UserResource::collection(User::with('game')->get()->sortBy('game.current_global_score',SORT_ASC,true)->values());
    }

there is an accessor on Game model

public function getCurrentGlobalScoreAttribute()
    {
        return $this->statuses()->latest()->first()->global_score;
    }

this is the relation between the User model and Game model

   public function game(): HasOne
    {
        return $this->hasOne(Game::class);
    }

I want to sort the users with their global score in the game, it's actually returning users but not sorted

0 likes
5 replies
vincent15000's avatar

Perhaps you should retrieve the collection and then sort by the needed field in your collection.

public function sortByScore()
{
	$resource = UserResource::collection(User::with('game')->get());
	return $resource->sortBy('game.current_global_score'); // here it depends on the fields present in your resource
}
Tray2's avatar

@vincent15000 No, that is bad advice. Sorting a collection should be avoided if possible.

To sort on another table you need to use join.

See example.

User::select(['users.name',  'role_name'])
			->join('role_user','users.id','=','role_user.user_id')
			->join('roles', 'roles.id','=','role_user.role_id')
			->orderBy('role_names','desc')
			->get()
1 like
Sinnbeck's avatar

@vincent15000 Because it is waaay faster to do it in the database, and has less memory usage as well :)

1 like

Please or to participate in this conversation.