Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Enum Laravel Package

spatie/laravel-enum

Laravel integration for spatie/enum: use Enum base class in Laravel, cast model attributes to enums (including nullable and arrays), and get Laravel-friendly behavior via custom casts and Castable support for Eloquent.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Type Safety & Domain Modeling: The package extends Laravel’s native support for PHP enums (introduced in PHP 8.1) by providing a fluent, expressive API for defining and using enums in Laravel contexts (e.g., Eloquent models, validation, API responses). This aligns well with modern Laravel applications prioritizing strong typing, self-documenting code, and reduced magic strings.
  • Separation of Concerns: Enums defined via spatie/laravel-enum can encapsulate business logic (e.g., validation rules, database constraints, or API serialization) within the enum itself, improving maintainability.
  • Laravel Ecosystem Synergy: Seamlessly integrates with:
    • Eloquent models (via Enum trait or HasEnums).
    • Form requests/validation (via EnumRule).
    • API resources (via EnumResource).
    • Database migrations (via EnumColumn).
    • Localization (via EnumTranslations).
  • Backward Compatibility: Works alongside legacy string-based enums or raw integers, easing migration.

Integration Feasibility

  • Low Friction: Installation is a single Composer command with minimal configuration. The package auto-discovers enums via PSR-4 autoloading.
  • Database Agnostic: Supports all major databases (MySQL, PostgreSQL, SQLite) with minimal schema changes (e.g., tinyint or string columns).
  • Testing Support: Includes helpers for unit/feature testing (e.g., Enum::from() assertions).
  • IDE-Friendly: Enums are first-class PHP types, enabling autocompletion and static analysis (e.g., PHPStan, Psalm).

Technical Risk

  • PHP Version Dependency: Requires PHP 8.1+ (for native enums). Risk if the codebase is on PHP 8.0 or lower.
  • Enum Bloat: Overuse of enums for simple values (e.g., active/inactive) may add unnecessary complexity. Mitigate by reserving enums for non-trivial domains (e.g., OrderStatus, PaymentMethod).
  • Migration Overhead: Existing string/integer-based enums must be refactored to the new syntax (e.g., class Status extends Enum instead of const ACTIVE = 'active'). Use database migrations and feature flags to phase this in.
  • Caching Implications: Enums are loaded at runtime. For performance-critical paths, ensure enums are eager-loaded or cached (e.g., via Laravel’s app() container).
  • Third-Party Conflicts: Rare, but potential naming collisions with existing Enum classes (e.g., custom Enum traits). Use fully qualified namespaces to avoid clashes.

Key Questions

  1. Adoption Scope:
    • Which parts of the codebase will use enums? (e.g., Eloquent models, API layers, validation).
    • Are there legacy systems using string/integer enums that need gradual migration?
  2. Performance:
    • Will enums be used in high-frequency queries (e.g., WHERE status = ?)? If so, test database indexing strategies.
  3. Team Readiness:
    • Is the team familiar with PHP 8.1+ enums? If not, budget for training or documentation.
  4. Testing Strategy:
    • How will enum-based logic be tested? (e.g., unit tests for enum methods, feature tests for API responses).
  5. Localization:
    • Are enums used in user-facing labels? If yes, leverage EnumTranslations for i18n support.
  6. Monitoring:
    • How will invalid enum values (e.g., database corruption) be detected? Consider database constraints or application-level validation.

Integration Approach

Stack Fit

  • Laravel Core: Native integration with Eloquent, Validation, and API Resources reduces boilerplate.
  • PHP 8.1+: Leverages native enums for type safety and performance.
  • Database: Works with any Laravel-supported database (no vendor lock-in).
  • Testing: Compatible with Pest, PHPUnit, and Laravel’s testing helpers.
  • Tooling: Supports IDE autocompletion, static analysis (PHPStan), and mutation testing (Infection).

Migration Path

  1. Assessment Phase:
    • Audit existing string/integer enums (e.g., via grep or static analysis).
    • Prioritize enums by business criticality and refactoring effort.
  2. Pilot Phase:
    • Migrate a non-critical module (e.g., a feature flag or internal tool).
    • Test with CI/CD pipelines and manual QA.
  3. Gradual Rollout:
    • Database-First: Update migrations to use EnumColumn for new fields.
    • Code-First: Replace string constants with spatie/laravel-enum classes in models/validation.
    • API-First: Update API responses to use EnumResource for type-safe serialization.
  4. Deprecation Phase:
    • Add deprecation warnings for old enum usage.
    • Phase out legacy enums in favor of new ones.

Compatibility

  • Laravel Versions: Supports Laravel 9+ (tested up to latest stable).
  • PHP Extensions: No additional extensions required beyond native enums.
  • Database Drivers: Works with all Laravel-supported databases (MySQL, PostgreSQL, SQLite, SQL Server).
  • Caching: Enums are cached by Laravel’s service container by default. For custom caching, implement Spatie\Enum\EnumInterface.

Sequencing

  1. Prerequisites:
    • Upgrade to PHP 8.1+ and Laravel 9+.
    • Ensure CI/CD pipelines support the new PHP version.
  2. Core Integration:
    • Install spatie/laravel-enum and publish config (if needed).
    • Define enums in app/Enums/ namespace.
  3. Database Changes:
    • Update migrations to use EnumColumn for new fields.
    • For existing tables, add constraints or use casts in models.
  4. Application Logic:
    • Replace string/integer enums with Spatie\Enum\Enum classes.
    • Update validation rules, API responses, and business logic.
  5. Testing:
    • Write unit tests for enum methods (e.g., isValid()).
    • Test integration with Eloquent, validation, and API layers.
  6. Monitoring:
    • Add logging for invalid enum values (e.g., in app/Exceptions/Handler.php).
    • Set up alerts for database constraint violations.

Operational Impact

Maintenance

  • Reduced Boilerplate: Enums centralize logic (e.g., validation, serialization), reducing duplicate code.
  • Easier Refactoring: Changing an enum’s values requires updates in one place (the enum class) vs. multiple files.
  • Documentation: Enums serve as self-documenting types (e.g., OrderStatus::PENDING vs. 1).
  • Dependency Management:
    • Single Composer package with minimal updates (follows SemVer).
    • Underlying spatie/enum package is battle-tested (used in 100+ projects).

Support

  • Debugging: Enums provide clear error messages (e.g., Invalid enum value: 'invalid_status').
  • Troubleshooting:
    • Use dd($enum->getValue()) to inspect enum states.
    • Leverage Laravel’s exception handling for invalid values.
  • Community: Active GitHub repo with 364 stars and recent releases (2025-02-25).
  • Commercial Support: Spatie offers paid support for enterprise users.

Scaling

  • Performance:
    • Enums are lightweight (no runtime overhead beyond native PHP enums).
    • Database queries benefit from indexed enum columns (e.g., tinyint for small sets).
  • Horizontal Scaling: No shared state; enums are stateless and thread-safe.
  • Caching: Enums are cached by Laravel’s container. For large applications, consider eager-loading critical enums in a service provider.

Failure Modes

  • Invalid Data:
    • Mitigation: Use database constraints (ENUM type or CHECK constraints) + application validation.
    • Fallback: Log invalid values and default to a safe state (e.g., OrderStatus::CANCELLED).
  • Database Corruption:
    • Risk: Invalid values in enum columns (e.g., due to manual SQL).
    • Mitigation: Use Spatie\Enum\EnumColumn with strict validation.
  • Enum Bloat:
    • Risk: Overusing enums for simple values (e.g., true/false).
    • Mitigation: Reserve enums for non-trivial domains with >3 values.
  • Migration Failures:
    • Risk: Breaking changes during enum refactoring.
    • Mitigation: Use feature flags and database backups.

**

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport