Skip to content

[13.x] fix bug: enhance handling of empty values in grouping #55875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

comes
Copy link
Contributor

@comes comes commented May 27, 2025

Description

This PR fixes a bug within groupBy in collections. I understand it can be considered as a breaking change in 12.x, so maybe worth to consider to fix this issue in 13.x

How to reproduce

Prepare an array with some values, for demoing reasons, it's easier to spot the bug with preserveKeys: true enabled.

collect([
  10 => [],
  20 => ['user' => 2, 'roles' => []], // missing
  30 => ['user' => 3, 'roles' => [null]],
  40 => ['user' => 4, 'roles' => ['Role_2']]
])->groupBy('roles', preserveKeys: true)
  ->dump();

The output after grouping missing key 20, because of roles is an empty array, while key 30 is an array with a single value of null.

Solution

Inside groupBy function, treat any empty array returned as a grouping key to null before processing. This ensures that items with an empty array are grouped under the “null” bucket rather than being skipped.

@taylorotwell taylorotwell marked this pull request as draft May 27, 2025 21:44
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.

1 participant