Laravel: Get the right totals using aggregate queries such as count(), avg(), etc

Laravels fluent query markup makes life real easy, too easy sometimes.

Getting $query->groupBy(‘column’)->count() to spit out the correct count for the recordset instead of the total before the aggregate took me a few minutes to figure out, so I thought I’d share.

Imagine the following were rows of the Persons table:

['name' => 'Tom', 'age' => '30']

['name' => 'Harry', 'age' => '30']

['name' => 'Ben', 'age' => '29']

Output:

Person::groupBy('age')->count() // Incorrectly outputs 3

Person::groupBy('age')->count(DB::raw('DISTINCT age')) // Correctly outputs 2


Leave a Reply

Your email address will not be published. Required fields are marked *