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

Doctrine Enum Type Laravel Package

acelaya/doctrine-enum-type

Doctrine DBAL type for mapping MyCLabs\Enum\Enum values to entity columns. Provides a reusable PhpEnumType to register enums as custom Doctrine types. Note: largely obsolete now that PHP has native enums and Doctrine supports them.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require acelaya/doctrine-enum-type:^2.5.0
    

    Ensure myclabs/php-enum is installed (dependency). This version now supports doctrine/dbal 3.0.

  2. Register the Type Add to your Doctrine orm.xml or EntityManager configuration:

    <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
            http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
        <driver name="enum_driver" class="Acelaya\DoctrineEnumType\EnumTypeDriver"/>
    </doctrine-mapping>
    
  3. First Use Case Define an enum (e.g., UserRole.php):

    use MyCLabs\Enum\Enum;
    
    class UserRole extends Enum
    {
        const ADMIN = 'admin';
        const USER = 'user';
    }
    

    Apply it to an entity field:

    use Doctrine\ORM\Mapping as ORM;
    use Acelaya\DoctrineEnumType\Type\EnumType;
    
    #[ORM\Entity]
    class User
    {
        #[ORM\Column(type: EnumType::NAME, enumType: UserRole::class)]
        private $role;
    }
    

Implementation Patterns

Workflow: CRUD with Enums

  1. Saving Enums

    $user = new User();
    $user->setRole(UserRole::ADMIN); // Stores 'admin' in DB
    $em->persist($user);
    
  2. Querying Enums

    $admins = $em->createQueryBuilder()
        ->from(User::class, 'u')
        ->where('u.role = :role')
        ->setParameter('role', UserRole::ADMIN)
        ->getQuery()
        ->getResult();
    
  3. Form Handling (Symfony)

    use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
    
    $builder->add('role', ChoiceType::class, [
        'choices' => UserRole::toArray(), // ['admin' => 'admin', 'user' => 'user']
    ]);
    

Integration Tips

  • Migrations: Use raw SQL for enum columns (Doctrine doesn’t auto-generate them):
    Schema::create('users', function (Blueprint $table) {
        $table->enum('role', ['admin', 'user']);
    });
    
  • Validation: Combine with Symfony Validator:
    use Symfony\Component\Validator\Constraints as Assert;
    
    #[ORM\Column(type: EnumType::NAME, enumType: UserRole::class)]
    #[Assert\Type(type: UserRole::class)]
    private $role;
    
  • Serialization: Enums auto-convert to strings in JSON (Laravel API resources).
  • DBAL 3.0 Compatibility: This version explicitly supports doctrine/dbal 3.0, ensuring compatibility with modern Doctrine setups.

Gotchas and Tips

Pitfalls

  1. Archived Package Risk

  2. Enum Class Naming

    • Doctrine expects enum classes to be namespaced (e.g., App\Enum\UserRole). Underscore-separated enums (e.g., User_Role) may fail silently.
  3. Case Sensitivity

    • Database enum values must match the enum constant case (e.g., ADMINadmin). Use strtoupper() if the DB defaults to uppercase.
  4. Hybrid Properties

    • Avoid mixing @ORM\Column(type: EnumType::NAME) with @ORM\Column(type: 'string') on the same field.
  5. DBAL Version Mismatch

    • If using doctrine/dbal < 3.0, this package may not work. Downgrade to acelaya/doctrine-enum-type:^2.4 if needed.

Debugging

  • Invalid Enum Values
    • Throws InvalidArgumentException if a DB value isn’t in the enum. Validate with:
      if (!UserRole::isValid($value)) { /* handle error */ }
      
  • Query Builder Issues
    • Use EnumType::NAME in DQL (not the enum class name):
      ->where('u.role = :role')
      ->setParameter('role', UserRole::ADMIN->value) // or ->getValue()
      

Extension Points

  1. Custom Enum Types Override Acelaya\DoctrineEnumType\Type\EnumType for non-MyCLabs enums (e.g., Spatie enums).

  2. Database-Specific Quirks

    • MySQL: Supports native ENUM type (optimized storage).
    • PostgreSQL: Use text type with a check constraint:
      $table->string('role')->constraint('role', ['admin', 'user']);
      
  3. Laravel-Specific

    • For Eloquent, pair with spatie/laravel-enum for seamless casting:
      use Spatie\LaravelEnum\HasEnums;
      
      class User extends Model
      {
          use HasEnums;
          protected $casts = ['role' => UserRole::class];
      }
      
  4. CI/CD Updates

    • The package now uses GitHub Actions for builds (replacing Travis CI). Forks may need CI adjustments.
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php