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 Mapper Laravel Package

adrenalinkin/enum-mapper

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adrenalinkin/enum-mapper
    

    No additional configuration is required—just autoload the package.

  2. Basic Usage Define an enum-like class (e.g., UserRole.php):

    use Adrenalinkin\EnumMapper\EnumMapper;
    
    class UserRole extends EnumMapper
    {
        protected static $map = [
            'admin' => 'Administrator',
            'user'  => 'Regular User',
            'guest' => 'Guest',
        ];
    
        protected static $default = 'user';
    }
    

    Use it in your application:

    // Convert to human-readable
    $role = UserRole::get('admin'); // Returns "Administrator"
    
    // Convert back to database value
    $dbValue = UserRole::getKey('Administrator'); // Returns "admin"
    
  3. First Use Case Replace hardcoded strings in controllers/models with mapped values:

    // Before
    if ($user->role === 'admin') { ... }
    
    // After
    if (UserRole::get($user->role) === 'Administrator') { ... }
    

Implementation Patterns

Workflows

  1. Database Integration Use with Eloquent models to enforce consistency:

    class User extends Model
    {
        protected $casts = [
            'role' => UserRole::class, // Automatically maps DB value to enum
        ];
    }
    
  2. Validation Leverage the mapper in Form Requests:

    use Adrenalinkin\EnumMapper\Rules\ValidEnum;
    
    public function rules()
    {
        return [
            'role' => ['required', new ValidEnum(UserRole::class)],
        ];
    }
    
  3. API Responses Transform enum keys to human-readable labels in JSON:

    return response()->json([
        'role' => UserRole::get($user->role),
    ]);
    

Integration Tips

  • Localization: Extend the mapper to support translations:
    class UserRole extends EnumMapper
    {
        protected static $map = [
            'admin' => trans('roles.admin'),
            // ...
        ];
    }
    
  • Dynamic Enums: Use for dynamic configurations (e.g., settings):
    class SiteStatus extends EnumMapper
    {
        protected static $map = [];
        public static function setMap(array $map) {
            static::$map = $map;
        }
    }
    
  • Middleware: Restrict routes by enum values:
    public function handle($request, Closure $next)
    {
        if (!UserRole::has('admin', $request->user()->role)) {
            abort(403);
        }
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity Database values must match enum keys exactly (e.g., 'ADMIN''admin'). Use strtolower() if needed:

    UserRole::get(strtolower($dbValue));
    
  2. Default Fallback If $default is undefined and an invalid key is passed, get() returns null. Set a default:

    protected static $default = 'user'; // Fallback to 'user' if invalid
    
  3. Static Nature Avoid instantiating the mapper directly—all methods are static. ❌ Bad:

    $role = new UserRole(); // Fails
    

Debugging

  • Invalid Keys: Use has() to check validity before conversion:
    if (!UserRole::has($dbValue)) {
        throw new \InvalidArgumentException("Invalid role: {$dbValue}");
    }
    
  • Missing Maps: If get() returns null, verify $map is populated and keys match.

Extension Points

  1. Custom Logic Override get() or getKey() for business rules:

    public static function get($key, $default = null)
    {
        if ($key === 'legacy_admin') {
            return parent::get('admin', $default);
        }
        return parent::get($key, $default);
    }
    
  2. Database Storage Store enum keys as integers (e.g., 1 for 'admin') by extending the mapper:

    class NumericUserRole extends EnumMapper
    {
        protected static $numericMap = [
            1 => 'admin',
            2 => 'user',
        ];
        public static function getKey($value) {
            return array_search($value, static::$map, true) + 1;
        }
    }
    
  3. Performance Cache mapped values in production:

    $cachedRole = cache()->remember("role_{$dbValue}", 3600, fn() => UserRole::get($dbValue));
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui