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

Uuid Doctrine Laravel Package

ramsey/uuid-doctrine

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ramsey/uuid-doctrine:^2.1
    

    Ensure ramsey/uuid (v6.x+) and doctrine/dbal (v4.x+) are installed. PHP 8.1+ is now required (breaking change).

  2. Register the Type in Doctrine Add the following to your config/doctrine.php (or equivalent):

    'types' => [
        'uuid' => Ramsey\UuidDoctrine\Types\UuidType::class,
    ],
    
  3. First Use Case: UUID Entity Field

    use Ramsey\UuidDoctrine\Types\UuidType;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class User
    {
        #[ORM\Id]
        #[ORM\Column(type: 'uuid', unique: true)]
        #[ORM\GeneratedValue(strategy: 'CUSTOM')]
        #[ORM\CustomIdGenerator(class: 'Ramsey\UuidDoctrine\UuidGenerator')]
        private ?string $id = null;
    }
    
  4. Generate a UUID Use the UuidGenerator in your repository or service:

    $uuid = Uuid::uuid4()->toString(); // ramsey/uuid (v6.x+)
    $entity->setId($uuid);
    

Implementation Patterns

Common Workflows

  1. UUID as Primary Key

    • Use #[ORM\GeneratedValue(strategy: 'CUSTOM')] with Ramsey\UuidDoctrine\UuidGenerator.
    • Example:
      #[ORM\Id]
      #[ORM\Column(type: 'uuid')]
      #[ORM\GeneratedValue(strategy: 'CUSTOM')]
      #[ORM\CustomIdGenerator(class: 'Ramsey\UuidDoctrine\UuidGenerator')]
      private ?string $id;
      
  2. UUID as Foreign Key

    • Reference UUID fields in relationships:
      #[ORM\ManyToOne(targetEntity: User::class)]
      #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false)]
      private ?User $owner;
      
  3. UUID in DTOs/Queries

    • Use UuidType in DTOs or API filters:
      use Ramsey\UuidDoctrine\Types\UuidType;
      
      class UserFilter
      {
          #[Assert\Type(type: UuidType::class)]
          public ?string $id;
      }
      
  4. Bulk Inserts with UUIDs

    • Generate UUIDs in batches for performance:
      $uuids = array_map(fn() => Uuid::uuid4()->toString(), range(1, 1000));
      

Integration Tips

  • Symfony Forms: Use UuidType in form fields:
    $builder->add('id', UuidType::class, ['disabled' => true]);
    
  • API Responses: Serialize UUIDs as strings (default behavior).
  • Database Migrations:
    • PostgreSQL: Supports native binary UUIDs (v2.1.0+). Use options: ['postgresql_uuid_binary' => true] for binary storage.
    • MySQL 8+: Use UUID type; older versions require CHAR(36).
    • SQLite: Requires CHAR(36).
  • Doctrine DBAL v4: Fully supported (no breaking changes for most use cases).

Gotchas and Tips

Pitfalls

  1. Database Compatibility

    • PostgreSQL: Binary UUID support is now fixed (v2.1.0). Enable with:
      #[ORM\Column(type: 'uuid', options: ['postgresql_uuid_binary' => true])]
      
      Requires PostgreSQL 12+ and doctrine/dbal v4.x.
    • MySQL < 8.0: Use CHAR(36) instead of UUID type.
    • SQLite: Always use CHAR(36) for UUIDs.
  2. ORM Quirks

    • Avoid #[ORM\GeneratedValue(strategy: 'AUTO')]—use CUSTOM with UuidGenerator.
    • UUIDs are not auto-incremented; generate them manually or via UuidGenerator.
  3. PHP Version Requirement

    • Minimum PHP 8.1 is now required (breaking change). Update your environment if using PHP < 8.1.
  4. Serialization Issues

    • Ensure UUIDs are stored as strings (not binary) unless using PostgreSQL binary mode.
    • Avoid casting to UuidInterface unless necessary (use Uuid::fromString()).
  5. Doctrine DBAL v4

    • If using custom DBAL configurations, verify compatibility with v4.x. Most use cases remain unchanged.

Debugging Tips

  • Invalid UUIDs: Use Uuid::isValid() to validate input.
  • Doctrine Errors: Ensure Ramsey\UuidDoctrine\Types\UuidType is registered in Doctrine’s type system.
  • PostgreSQL Binary Issues: If using binary UUIDs, confirm your connection pool (e.g., PgBouncer) supports binary resources.
  • Migration Failures: Verify DB column type matches (e.g., UUID vs. CHAR(36)).

Extension Points

  1. Custom UUID Generation Override UuidGenerator for specific formats (e.g., namespaced UUIDs):

    class CustomUuidGenerator extends UuidGenerator
    {
        public function generate(ExecutionContext $context, ?object $entity): string
        {
            return Uuid::uuid5(Uuid::NAMESPACE_DNS, 'custom.prefix')->toString();
        }
    }
    
  2. Custom Type Validation Extend UuidType for stricter validation (e.g., reject nil UUIDs):

    class StrictUuidType extends UuidType
    {
        public function convertToDatabaseValue($value, AbstractPlatform $platform)
        {
            if (empty($value)) {
                throw new \InvalidArgumentException('UUID cannot be empty.');
            }
            return parent::convertToDatabaseValue($value, $platform);
        }
    }
    
  3. Hybrid UUID Fields Use #[ORM\Column(type: 'string')] with UuidType for non-Doctrine contexts:

    #[ORM\Column(type: 'string')]
    #[Assert\Type(type: UuidType::class)]
    private ?string $externalId;
    
  4. PostgreSQL Binary UUIDs (v2.1.0+) Leverage PostgreSQL’s native binary UUID support:

    #[ORM\Column(type: 'uuid', options: ['postgresql_uuid_binary' => true])]
    private ?string $id;
    

    Requires PostgreSQL 12+ and doctrine/dbal v4.x for optimal performance.

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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