Power-Components / livewire-powergrid

⚡ PowerGrid generates modern, powerful and easy-to-customize data tables using Laravel Livewire.
https://livewire-powergrid.com
MIT License
1.46k stars 215 forks source link

[Enhancement] Column casted as enum #1365

Closed luanfreitasdev closed 6 months ago

luanfreitasdev commented 7 months ago

Discussed in https://github.com/Power-Components/livewire-powergrid/discussions/1353

Originally posted by **eafarooqi** January 25, 2024 ### Have you searched through other issues to see if your problem is already reported or has been fixed? Yes, I did not find it. ### Did you read the documentation? Yes, I did not find it. ### Have you tried to publish the views? Yes - I didn't work. ### Is there an error in the console? No ### PHP Version 8.1.0 ### PowerGrid 5.3.1 ### Laravel 10.42.0 ### Livewire 3.4.1 ### Alpine JS 3.12.0 ### Theme Bootstrap ### Describe the bug. I have an enum field which is include in the $cast attribute as enum. As per document i am getting the following error. "Male" is not a valid backing value for enum "App\Enums\Person\Gender" - cast property in model ``` protected $casts = [ 'gender' => Gender::class, ]; ``` - Gender enum ``` enum Gender: string { use EnumToCollectionTrait; case MALE = 'M'; case FEMALE = 'F'; public function label(): string { return match($this) { self::MALE => 'Male', self::FEMALE => 'Female', }; } } ``` - Column ``` ->addColumn('gender', function (Person $person) { return Gender::tryFrom($person->gender->value)->label(); }); ``` This only works when cast is removed from the model and column is changed to as follows (as in documentation). But i cannot remove the cast. ``` return Gender::tryFrom($person->gender)->label(); ``` - Have also tried with cast property as enum. ``` ->addColumn('gender', function (Person $person) { return $person->gender->value; }); ``` getting the following error in this case. preg_replace(): Argument # 3 ($subject) must be of type array|string, App\Enums\Person\Gender given or as follows ``` ->addColumn('gender', function (Person $person) { return $person->gender->label(); }); ``` The error is same as the first one. "Male" is not a valid backing value for enum "App\Enums\Person\Gender" ### To Reproduce... Add enum column to the cast propery in model.