Ad

Where Function Query Withcount Not Working Laravel

- 1 answer

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

Ad

Answer

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'
} else {
    $order = 'review_count'
}

return Webinar::query()
->withCount('users')->orderByDesc($order)
->get();
Ad
source: stackoverflow.com
Ad