Skip to content
Advertisement

How can i get the order of parents using number of child data in laravel

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);

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement