Home > Software engineering >  How can i get the order of parents using number of child data in laravel
How can i get the order of parents using number of child data in laravel

Time:01-23

I want to get the order of Users table on the basis of roles.. for example if user has three roles its comes first, then user of two roles comes and so on her it is my query but it gives order to role table not parent table

$users = User::with(['roles'=>function($query){
        $query->orderBy('id','desc');
    }])->get();
    dd($users);

CodePudding user response:

You can use withCount method and order the results

$users =  User::query()
    ->withCount([
        'roles as no_of_roles_for_user'
    ])
    ->orderByDesc('no_of_roles_for_user')
    ->get();
  •  Tags:  
  • Related