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

Enum Laravel Package

commerceguys/enum

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require commerceguys/enum
    

    No additional configuration is required—it’s a standalone library.

  2. First Use Case: Define an Enum Create a basic enum class (e.g., UserRole.php):

    use CommerceGuys\Enum\AbstractEnum;
    
    class UserRole extends AbstractEnum
    {
        const ADMIN = 'admin';
        const EDITOR = 'editor';
        const VIEWER = 'viewer';
    
        protected static $values = [
            self::ADMIN,
            self::EDITOR,
            self::VIEWER,
        ];
    }
    

    Use it in your code:

    $role = UserRole::from('admin'); // Returns UserRole instance
    echo $role->getValue(); // Outputs: 'admin'
    
  3. Key Methods to Explore First

    • from($value): Convert a string/value to an enum instance.
    • isValid($value): Check if a value is valid for the enum.
    • getValues(): Get all allowed values as an array.
    • getValue(): Get the raw value of the enum instance.

Implementation Patterns

Workflows

  1. Validation Replace manual string checks with enum validation:

    if (UserRole::isValid($request->input('role'))) {
        $role = UserRole::from($request->input('role'));
    }
    
  2. Database Integration Use enums for Eloquent model attributes:

    class User extends Model
    {
        protected $casts = [
            'role' => UserRole::class, // Automatically casts to UserRole enum
        ];
    }
    

    Laravel’s casts will handle serialization/deserialization.

  3. API Responses Return enum values in JSON responses:

    return response()->json([
        'role' => $user->role->getValue(), // 'admin', 'editor', etc.
    ]);
    
  4. Switch Statements Replace magic strings with type-safe enums:

    switch ($user->role->getValue()) {
        case UserRole::ADMIN:
            // Handle admin logic
            break;
        case UserRole::EDITOR:
            // Handle editor logic
            break;
    }
    

Integration Tips

  • Laravel Service Providers: Register enums as singleton bindings if reused across the app:
    $this->app->singleton(UserRole::class, function () {
        return UserRole::from('default');
    });
    
  • Form Requests: Validate enums in Laravel Form Requests:
    public function rules()
    {
        return [
            'role' => ['required', Rule::in(UserRole::getValues())],
        ];
    }
    
  • Blade Templates: Use enums for dynamic UI logic:
    @if($user->role === UserRole::ADMIN)
        <button>Admin Actions</button>
    @endif
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity Enum values are case-sensitive by default. Use strtolower() or strtoupper() if needed:

    UserRole::from(strtolower($input)); // Force lowercase
    
  2. Duplicate Values Ensure self::$values contains unique values—duplicates will cause issues during validation.

  3. Serialization Quirks Enums may not serialize/deserialize cleanly in some contexts (e.g., Redis). Cast to raw values explicitly:

    $serialized = $user->role->getValue(); // Store this instead of the enum
    
  4. AbstractEnum Inheritance Extend AbstractEnum directly. Avoid intermediate abstract classes unless necessary.

Debugging

  • Invalid Values Use isValid() before from() to avoid exceptions:
    if (!UserRole::isValid($value)) {
        throw new \InvalidArgumentException("Invalid role: {$value}");
    }
    
  • Unexpected Behavior Override getValue() or isValid() if custom logic is needed (e.g., for legacy systems).

Extension Points

  1. Custom Validation Extend AbstractEnum to add validation rules:

    class UserRole extends AbstractEnum
    {
        protected static function validateValue($value)
        {
            if (strlen($value) > 10) {
                throw new \InvalidArgumentException("Role too long");
            }
            return parent::validateValue($value);
        }
    }
    
  2. Dynamic Enums Load values from a database or config:

    class DynamicRole extends AbstractEnum
    {
        protected static $values;
    
        public static function loadFromConfig()
        {
            self::$values = config('roles.available');
        }
    }
    DynamicRole::loadFromConfig();
    
  3. Backward Compatibility For PHP < 5.6, use getValues() instead of [] syntax:

    $values = UserRole::getValues(); // Array of strings
    
  4. Performance Cache enum instances if instantiated frequently:

    static $instances = [];
    public static function from($value)
    {
        if (!isset(self::$instances[$value])) {
            self::$instances[$value] = parent::from($value);
        }
        return self::$instances[$value];
    }
    
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.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views