Laravel Eloquent groupBy() AND also return count of each group

Since this is the top result when i search for eloquent count with groupby returns only first

using "illuminate/database": "^9.38" in composer. so “should” be the latest at the time of this post

I honestly have no idea why they think that returning the first record is the right option.. ie

IMHO the current implementation doesn’t make sense for queries including groupBy statements.
Why should be N_1 be the “right” result?

Since @taylorotwell rightly pointed out some performance issues with counting the subquery results, why don’t we fix that on the php side, by checking if there are any group statements, and if so, performing a N_1 + N_2 + …. + N_M ?

https://github.com/laravel/ideas/issues/1693#issuecomment-621167890

Wrapping the query and doing a count seems to work for me

$records = ...

$record_count = DB::table( "fake" );
$record_count->fromSub($records->select(DB::raw(1)),"query");
$record_count->count();
  • create a “fake” query builder
  • add a sub “from” from (…) query set the “sub query” to select 1 instead of returning huge column data. not sure if this is needed but in my mind it seems like a good idea
  • do the normal ->count()

returns the “expected” result since it executes:

select count(*) as aggregate from (select 1 from ... group by ...) as `query`

The sub is the “query” that $records would normaly execute

My use-case is for pagination (not using laravel). so i get the record count then pass it to the paginator then call ->forPage()->get()

https://github.com/laravel/framework/issues/44081#issuecomment-1301816710

Alternate Text Gọi ngay