How to get user with lowest number of related entities?

The application has the possibility to contact support team. Representatives of the support service are users with the role Manager or administrator. Users I got:

$users = User::whereHas('roles', function ($query) {
 $query->whereIn('name', [
User::ROLE_ADMINISTRATOR,
User::ROLE_MANAGER
]);
})->get();


The newly created dialog (Chat) to bind to the user representative technical support with least amount attached chat (some balance). What is the best way to implement (I think in a loop to count the number of releasenew each user, and look for the minimum value, but perhaps there is a suitable collection method)?
June 3rd 19 at 21:00
2 answers
June 3rd 19 at 21:02
Something like this:
$user = UserModel::select([DB::raw('count(uc.id) as chats'), 'users.*'])
 ->join('user_chats as uc', 'uc.user_id', '=', 'users.id')
 ->orderByRaw(DB::raw("chats desc"))->first();
June 3rd 19 at 21:04
https://laravel.com/docs/5.6/eloquent-relationship... there is a method for linked tables withCount, add the sorting by that field.

Find more questions by tags Laravel