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?
Remove
count()
and then in your view
{{count($numberoftwits)}}
Or if you just want the count, remove the ->get();
$numberoftwits = DB::table('twits')
->groupBy('user_id')
->count();
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();
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 ;)
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
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
@Snapey actually i thought i was replaying
Please sign in or create an account to participate in this conversation.