0

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

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.