Where function query withcount not working Laravel

this works perfectly fine

return Webinar::query()
        ->withCount('users')->orderByDesc('users_count')
        ->get();

but I need to use a condition for sorting, but this doesnt work

return Webinar::query()
        ->where(function($query) use ($sort_by) {
             if($sort_by == 0) {
                  return $query->withCount('users')->orderByDesc('users_count');
             } else {
                  return $query->withCount('review')->orderByDesc('review_count');
             }
        })
        ->get();

I also tried a condition inside like this to check my if else function

return Webinar::query()
        ->where(function($query) use ($sort_by) {
             if($sort_by == 0) {
                  return $query->withCount('users')->orderByDesc('users_count')
                         ->where('status', 2);
             } else {
                  return $query->withCount('review')->orderByDesc('review_count')
                         ->where('status', 1);
             }
        })
        ->get();

but the where status is only working not withcount. I hope someone can answer, thank you so much


Solution 1:

How about you move condition code outside query

but I need to use a condition for sorting, but this doesnt work

if ($sort_by === 0) {
    $order = 'users_count';
    $count = 'users';
} else {
    $order = 'review_count';
    $count = 'review';
}

return Webinar::query()
->withCount('users')->orderByDesc($order)
->get();