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

Entity Behavior Uuid Laravel Package

cycle/entity-behavior-uuid

Cycle ORM behavior that adds first-class UUID columns using ramsey/uuid. Annotate entities with Uuid4 and map fields as type "uuid" (including primary keys) for automatic UUID handling in Cycle ORM models.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require cycle/entity-behavior-uuid

Add the behavior to your entity class:

use Cycle\Annotated\Annotation\Behavior;
use Cycle\EntityBehavior\UUID;

#[Behavior(UUID::class)]
class User {}
  1. First Use Case

    • Generate a UUID for a new entity:
      $user = new User();
      $user->id; // Returns a UUID string (e.g., "123e4567-e89b-12d3-a456-426614174000")
      
    • Query by UUID:
      $user = $orm->getRepository(User::class)->find('123e4567-e89b-12d3-a456-426614174000');
      
  2. Where to Look First


Implementation Patterns

Workflows

  1. UUID Generation

    • Default: Uses Ramsey\Uuid\Uuid::uuid4() (auto-injected via DI).
    • Customize via constructor:
      $behavior = new UUID(new CustomUuidGenerator());
      
  2. Database Schema

    • Ensure your table has a uuid-ossp or uuid column type (PostgreSQL/MySQL):
      -- PostgreSQL
      CREATE TABLE users (
          id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
          ...
      );
      
    • For other databases, use a string column with length 36 (standard UUIDv4).
  3. Schema Integration (New in 1.2.0) Define UUID fields directly in your ORM schema for declarative configuration:

    use Cycle\Annotated\Annotation\Entity;
    use Cycle\ORM\Schema;
    
    #[Entity]
    class User
    {
        #[Schema\Column(type: 'uuid', primary: true)]
        public string $id;
    }
    

    This automatically integrates with the UUID behavior, eliminating the need for manual annotations.

  4. Integration with Cycle ORM

    • Repositories: UUIDs work seamlessly with Cycle’s repository pattern.
      $user = $repository->findBy(['email' => 'test@example.com']);
      
    • Queries: Use UUIDs in where clauses:
      $query = $orm->getRepository(User::class)
          ->where('id', '=', '123e4567-e89b-12d3-a456-426614174000');
      
  5. Migrations

    • Use Cycle Migrations to alter tables:
      use Cycle\Migrations\Migration;
      
      class CreateUsersTable extends Migration
      {
          public function up(): void
          {
              $this->table('users')->addColumn('id', 'uuid', ['primary' => true]);
          }
      }
      
    • Schema-Based Migrations: Leverage the new schema integration to auto-generate migrations:
      $this->table('users')->addColumn('id', 'uuid', [
          'primary' => true,
          'default' => fn() => Uuid::uuid4()->toString(),
          'generated' => true, // Explicitly mark as generated
      ]);
      
  6. API Responses

    • Serialize UUIDs as strings (default) or convert to Ramsey\Uuid\Uuid objects:
      $user->id->toString(); // Force string output
      

Gotchas and Tips

Pitfalls

  1. Database Compatibility

    • MySQL/MariaDB: Requires uuid() extension or CHAR(36) column type.
      ALTER TABLE users MODIFY id CHAR(36) NOT NULL;
      
    • SQLite: Use TEXT with length 36 (no native UUID support).
  2. UUID Collisions

    • UUIDv4 collisions are astronomically unlikely (~1 in 2¹²²), but avoid UUIDv1 if you need time-based sorting.
  3. Performance

    • Indexing UUIDs as strings (e.g., CHAR(36)) is faster than binary in some databases.
    • Avoid generating UUIDs in bulk (e.g., batch inserts) unless necessary.
  4. Schema Integration (New in 1.2.0)

    • Breaking Change: If you were using manual annotations (#[Behavior(UUID::class)]), ensure your schema definitions align with the new declarative approach.
    • Migration: Existing projects may need to update schema definitions to avoid conflicts.
  5. Serialization

    • Some serializers (e.g., JSON) may not handle Ramsey\Uuid\Uuid objects by default. Use accessors:
      public function getIdAttribute(): string
      {
          return $this->id->toString();
      }
      

Debugging

  1. Missing UUIDs

    • Check if the behavior is properly annotated or defined in the schema:
      $entity->getBehavior(UUID::class); // Should return the behavior instance
      
    • Verify the database column type matches the behavior’s expectations.
  2. DI Container Issues

    • Ensure Ramsey\Uuid\UuidFactory is bound in your DI container:
      $container->bind(UuidFactory::class, fn() => Uuid::getFactory());
      
  3. Schema Conflicts

    • If using both annotations and schema definitions, ensure consistency to avoid behavior conflicts.
  4. Logging

    • Enable Cycle ORM logging to debug behavior execution:
      $orm->getConfig()->debug = true;
      

Tips

  1. Custom UUID Formats

    • Override the behavior to use UUIDv1 or other variants:
      #[Schema\Column(type: 'uuid', primary: true)]
      public string $id;
      
      // In your entity constructor or behavior setup:
      $behavior = new UUID(new UuidFactory(), Uuid::UUID1);
      
  2. Hybrid IDs

    • Combine UUIDs with auto-increment for performance-critical tables:
      #[Schema\Column(type: 'uuid', primary: true)]
      public string $id;
      
      #[Schema\Column(type: 'integer', autoIncrement: true)]
      public int $sortId;
      
  3. Testing

    • Mock UUID generation for predictable tests:
      $mockFactory = $this->createMock(UuidFactory::class);
      $mockFactory->method('uuid4')->willReturn(Uuid::fromString('test-uuid'));
      $behavior = new UUID($mockFactory);
      
  4. Extensions

    • Add validation rules for UUIDs in Laravel:
      use Illuminate\Validation\Rule;
      
      $request->validate([
          'id' => ['required', Rule::uuid()],
      ]);
      
  5. Schema-Based Workflows

    • Advantage: Centralize UUID configuration in schema definitions for consistency.
    • Example: Define a reusable schema for UUID fields:
      use Cycle\ORM\Schema;
      
      #[Schema\Column(type: 'uuid', primary: true)]
      public string $id;
      
      // Reuse in other entities:
      #[Schema\Column(type: 'uuid')]
      public string $externalId;
      
  6. Migration Helpers

    • Use Cycle’s Schema builder for UUID columns with generated defaults:
      $this->table('users')->addColumn('id', 'uuid', [
          'primary' => true,
          'default' => fn() => Uuid::uuid4()->toString(),
          'generated' => true,
      ]);
      

NO_UPDATE_NEEDED would not apply here due to the new schema integration feature. The assessment has been fully updated to reflect the changes in **1.2.0**.
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