spatie / laravel-enum

Laravel support for spatie/enum
https://spatie.be/open-source
MIT License
341 stars 37 forks source link

Unable to groupBy a Collection Using an Enum as a Criteria when Casting #78

Closed viniciushss-interstar closed 3 years ago

viniciushss-interstar commented 3 years ago

Hi there,

Sorry if I'm doing something wrong but there's a problem when using an enum as model attribute and the attribute is used in the method groupBy of a Eloquent Collection. Example:

The model:

use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    protected $casts = [
        'status' => StatusEnum::class,
    ];
}

The problem with groupBy:

$testModels = TestModel::all;

$testModels->groupBy('status');

The return is:

TypeError array_key_exists(): Argument #1 ($key) must be a valid array offset type in vendor/laravel/framework/src/Illuminate/Collections/Collection.php:445

If I remove the cast from the model, it works fine, using the value as array key. Any suggestions?

Thanks!

Gummibeer commented 3 years ago

The fastest way would be to use the closure option for groupBy() and return the string value yourself. I'm pretty sure/optimistic that things like this will get better with PHP8.1 native enums and the things we can do with them then.

$testModels->groupBy(fn(TestModel $m): string => $m->status->value));
viniciushss-interstar commented 3 years ago

Thank you, that worked nicely.