syntaxerron's avatar

Laravel Eloquent sorting through parent-child relationship

I have two models: User and Department

  • Department hasMany User
  • User belongsTo Department

I want to sort the users based on department name with pagination. But results are still not sorted.

$sortType = request("sortType") ?? "asc";

$users = User::with(["department" => function ($query) use ($sortType) {
        $query->orderBy("name", $sortType);
    }]);

$users = $users->paginate(10);
0 likes
2 replies
CorvS's avatar

@erron You have to use a join in order to achieve what you want. Right now you are simply ordering the departments and since there is only one for each user nothing happens.

1 like
syntaxerron's avatar
syntaxerron
OP
Best Answer
Level 5

Thanks to @corvs for the idea. I managed to solve it by this:

$users = $users->leftJoin('departments', 'users.department_id', '=', 'departments.id')
                    ->select('users.*')
                    ->orderBy('departments.name', $sortType);
$users = $users->paginate(10);

Please or to participate in this conversation.