Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ramher101's avatar

New on laravel (doing a query with groupby and count)

Snippet in the controller

$numberoftwits = DB::table('twits')
            ->groupBy('user_id')
            ->count()
            ->get();
        

mysql query

SELECT COUNT(*) FROM twits GROUP BY user_id

Error Call to a member function get() on integer

What should I do in order to pass the result of the query to the compact statement in the controller?

0 likes
8 replies
jdunsmore's avatar

Remove

count()

and then in your view

{{count($numberoftwits)}}
mvd's avatar

Or if you just want the count, remove the ->get();

$numberoftwits = DB::table('twits')
            ->groupBy('user_id')
            ->count();
1 like
ramher101's avatar
ramher101
OP
Best Answer
Level 1

both solutions didnt not work however I was able to solve the problem by using db raw

$numberoftwits = DB::table('twits')
                     ->select(DB::raw('count(*) as num'))
                     ->groupBy('user_ID')
                     ->get();

3 likes
mvd's avatar

Both solutions work well, in both situations you get the count/total records. In your last post you changed the query requirements, thats not what you asked ;)

1 like
ramher101's avatar

actually its just the same look at my expected mysql query, i just called db raw to call it as it is :) the problem is that Im using count() the wrong way

1 like
abdelrhman-saeed's avatar

i have 2 tables (posts, users) and they are related with user_id column, i wanted to get the count of the posts grouped by the user_id so i did this:

Post::all()->groupBy('user_id');

it will return a collection object key => value, the key is the user_id and the value is an array of posts that are related to that user

Please or to participate in this conversation.