Laravel sort user list by rank

时间:2016-08-31 17:07:53

标签: php laravel

I have the current problem: I do have different ranks in my Team module. A team can have managers, captains and players. Currently my listing function works as followed:

public function index()
{

    $team = Auth::user()->team->first();
    $rank_sort = array('manager', 'captain', 'member');
    $members = array();
    $rank = 'member';

    // Check if there the user is currently in a team
    if($team) {
        $members_db = $team->users()->get();

        // Sort it by the sorting feature
        foreach($rank_sort as $rank) {
            foreach($members_db as $member) {
                if($member->pivot->rank == $rank) {
                    $members[] = $member;
                }
            }
        }

        // Get the rank of the current logged in user
        $rank = $team->users->where('id', Auth::id())->first()->pivot->rank;
    }

    return view('team', [
        'team'      =>  $team,
        'members'   =>  $members,
        'rank'      =>  $rank
    ]);
}

What I now want to achieve to drop out the whole $members and $rank_sort stuff (by which it is sorted). The $rank_sort does include the right order, I've tried out the sortBy function of laravel which never resulted in the right result. I always got: Member, Manager, Mem, Mem, Mem, Captain

 $members = $members_db->sortBy(function($member) {
    return $member->pivot_rank;
 });

This didn't even sort anything. Any ideas?

0 个答案:

没有答案