Skip to content

Conversation

@aydinfatih
Copy link
Contributor

Related: #57738

The Illuminate\Database\Query\Builder::aggregate() method (used by count(), sum(), min(), max(), avg()) returns only the first row when combined with groupBy(). This behavior is incorrect, misleading, and inconsistent with SQL semantics.

Users expect:

  • count()number of groups
  • sum()sum of group totals
  • min()smallest group value

But Laravel returns only the first group's result.


Current (Buggy) Behavior

Post::groupBy('post_category_id')->count();

Generated SQL (Laravel)

SELECT COUNT(*) AS aggregate 
FROM `posts` 
GROUP BY `post_category_id`;
+-----------+
| aggregate |
+-----------+
|         3 |
|       459 |
+-----------+

Laravel Returns 3 // Only first row — WRONG if user expects group count

User confusion:
“SQL shows 2 groups, but Laravel returns 3?” → Actually returns first group count, not total or group count.

Steps To Reproduce

Example Data

-- Table: posts
+----+--------------------+---------+
| id | post_category_id   | title   |
+----+--------------------+---------+
|  1 |                  1 | Post A  |
|  2 |                  2 | Post B  |
|  3 |                  3 | Post C  |
+----+--------------------+---------+
Post::groupBy('post_category_id')->count(); // returns 1

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants