Currently, a collection groupBy() returns the same type of collection, containing the same type of collection: @return static<array-key, static<array-key, TValue>>. That's good for the base collection, of children that accept any type of TValue, but not for EloquentCollection, because that doesn't accept any type of TValue, but only Model: @template TModel of \Illuminate\Database\Eloquent\Model. So groupBy() should check for that (or EloquentCollection could overwrite groupBy()) to not return new static, but new Illuminate\Support\Collection.
Fixing might be super backward incompatible, but it is correcter. Workaround is pretty simple though: add in custom model collection (which everyone has, right?):
/** @return BaseCollection<array-key, $this> */
public function groupBy($groupBy, $preserveKeys = false) {
$groups = parent::groupBy($groupBy, $preserveKeys); // temporary 'impossible' EloquentCollection of EloquentCollections
return BaseCollection::make($groups->all());
}
Laravel Version
11.23.5
PHP Version
8.2.14
Description
Currently, a collection
groupBy()
returns the same type of collection, containing the same type of collection:@return static<array-key, static<array-key, TValue>>
. That's good for the base collection, of children that accept any type ofTValue
, but not forEloquentCollection
, because that doesn't accept any type of TValue, but onlyModel
:@template TModel of \Illuminate\Database\Eloquent\Model
. SogroupBy()
should check for that (orEloquentCollection
could overwritegroupBy()
) to not returnnew static
, butnew Illuminate\Support\Collection
.Steps To Reproduce
Fixing might be super backward incompatible, but it is correcter. Workaround is pretty simple though: add in custom model collection (which everyone has, right?):