Home > Software design >  how to count total replies and show them in descending order in Laravel
how to count total replies and show them in descending order in Laravel

Time:05-17

i have two table questions and replies. inside replies i am storing all the replies of the question so in my replies table i have field question id. i want to count number of replies against the question and want to show them in a descending order. such as the the question who has the most replies should come first. how i can count them and show them in descending order?

$data=DB::table('questions')
            ->join('replies', 'questions.id','=','replies.q_id')->get();

CodePudding user response:

$data=DB::table('questions')
        ->join('replies', 'questions.id','=','replies.q_id')
        ->groupBy('questions.id')
        ->select('questions.id' , DB::raw('COUNT(1) as total_replies'))
        ->orderByDesc('total_replies')
        ->get();
  • Related