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', [

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( as chats'), 'users.*'])
 ->join('user_chats as uc', 'uc.user_id', '=', '')
 ->orderByRaw(DB::raw("chats desc"))->first();
June 3rd 19 at 21:04 there is a method for linked tables withCount, add the sorting by that field.

Find more questions by tags Laravel