konekt/enum-eloquent
Laravel Eloquent casting for Konekt Enums. Add the CastsEnums trait and define a $enums map on your model to automatically convert attributes to Enum objects, supporting Konekt Enum 2–4 and Laravel 8–12.
Install the package via composer require konekt/enum-eloquent, ensuring konekt/enum (v2–4) is also present. Define an enum class extending \Konekt\Enum\Enum (e.g., OrderStatus with constants like PENDING, COMPLETED). In your Eloquent model, import and use the CastsEnums trait, then declare attributes to cast in $enums (e.g., 'status' => OrderStatus::class). From there, assign strings or enum instances to the attribute—Laravel will automatically hydrate it into an enum object on retrieval, enabling calls like $order->status->isCompleted().
$enums to declare state attributes (status, type, tier) for compile-time safety and IDE autocompletion—ideal for domain entities like Orders, Users, or Payments."Namespace\Resolver@method" syntax (e.g., 'role' => 'RoleResolver@enumClass') for package-level or multi-tenant models, letting consumers override the enum class via config—essential for reusable libraries.Form, add EnumsAreCompatibleWithLaravelForms alongside CastsEnums to prevent form fields from rendering labels instead of scalar values (e.g., "pending" instead of "Pending Order").create(), update(), find(), and relationship assignments—even when mixing scalar strings and enum instances in mass assignment.Rule::in(OrderStatus::values()) for explicit validation; the cast ensures invalid values are caught at persistence if validation is skipped (throwing UnexpectedValueException).'processing' when only 'pending', 'completed' exist) throws UnexpectedValueException. Always seed valid values or wrap hydration in try/catch for migration scenarios.VARCHAR—avoid MySQL ENUM type for portability and easier schema changes. This package operates at the PHP layer, independent of DB-level enum constraints.__DEFAULT ≠ Database Default: The enum’s __DEFAULT constant only affects PHP-side fallback (e.g., null → default enum instance). For persistence, set column default in migrations if needed.Class@method) require a static method returning a valid enum class. Misconfiguration causes cryptic Constant ... not found errors—test resolver output in tests or tinker.EnumsAreCompatibleWithLaravelForms causes forms to use the enum’s label (e.g., "Pending") instead of the stored value ("pending"), breaking updates—add it explicitly when using Collective.dd($enum->values()) to inspect all valid values, get_class($model->attr) to verify enum resolution, and enum::options() (if using konekt/enum’s helpers) for labels—especially handy when runtime resolvers are involved.How can I help you explore Laravel packages today?