Search code examples
laravellaravel-8laravel-query-builder

Count user_id in a table in Laravel


I want to use the following query.

SELECT `name`, COUNT(`user_id`) AS total, SUM(`status` = 'Done') as done 
    FROM posts GROUP BY `name`, `user_id`, `status`

But when I implemented this...

Post::selectRaw('count(user_id) as total')
    ->selectRaw('SUM(status = "Done") as done')
    ->groupBy('name')
    ->get();

My data table doesn't display any data. Is there something wrong in my query?


Solution

  • This should work:

    $posts = DB::table('posts')->select(DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Done") as done')->groupBy('name')->get();
    

    Since you didnt provide any info about the models, migrations or logic, im guessing that you have everything else set up correctly.

    Also the links that Mohamed Bdr added are great examples and I recommend checking them out.