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

broadway/uuid-generator

UUID generator utilities for your application, powered by ramsey/uuid. Includes a standard generator plus testing helpers for predictable UUIDs in tests. Comes with a runnable example script in the examples directory.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Add the package via Composer in your Laravel project:

    composer require broadway/uuid-generator
    

    Ensure your composer.json includes PHP 7.2+ and ramsey/uuid (auto-installed as a dependency).

  2. First Use Case: Generate a UUID in a Laravel model or service:

    use Broadway\UuidGenerator\UuidGenerator;
    
    $uuid = UuidGenerator::generate(); // Returns a Ramsey\Uuid\UuidInterface instance
    
  3. Where to Look First:

    • Examples: Check the examples/generate.php for basic usage.
    • API: The package wraps ramsey/uuid, so refer to its documentation for advanced features (e.g., UUID versions, formats).
  4. Laravel Integration: For Eloquent models, configure UUIDs as primary keys:

    use Illuminate\Database\Eloquent\Model;
    use Broadway\UuidGenerator\UuidGenerator;
    use Ramsey\Uuid\UuidInterface;
    
    class User extends Model
    {
        protected $keyType = 'string';
        public $incrementing = false;
        protected $primaryKey = 'uuid';
    
        protected static function boot()
        {
            parent::boot();
            static::creating(function ($model) {
                $model->uuid = UuidGenerator::generate()->toString();
            });
        }
    }
    

Implementation Patterns

Core Workflows

  1. UUID Generation:

    • Random UUIDs: Use UuidGenerator::generate() for default v4 UUIDs.
      $uuid = UuidGenerator::generate(); // e.g., "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"
      
    • String Conversion: Convert to string for storage/transmission:
      $uuidString = $uuid->toString();
      
  2. Testing Patterns:

    • Deterministic UUIDs: Generate predictable UUIDs for fixtures or assertions:
      $testUuid = UuidGenerator::generate(); // Same UUID across test runs (if seeded)
      $this->assertEquals('expected-uuid-string', $testUuid->toString());
      
    • UUID Validation: Assert UUID format in tests:
      $this->assertInstanceOf(UuidInterface::class, $uuid);
      
  3. Broadway Integration:

    • Event/Command IDs: Use UUIDs for Broadway message IDs:
      use Broadway\Domain\DomainMessage;
      
      $message = new DomainMessage(
          UuidGenerator::generate(),
          'user_created',
          ['user_id' => 123]
      );
      
  4. Database Storage:

    • Column Definition: Use uuid type in migrations (PostgreSQL/MySQL 8+):
      Schema::create('users', function (Blueprint $table) {
          $table->uuid('uuid')->primary();
          $table->string('name');
          $table->timestamps();
      });
      
    • Retrieval: Cast UUIDs automatically in Eloquent:
      protected $casts = [
          'uuid' => 'string', // or use a custom accessor
      ];
      

Integration Tips

  1. Service Container: Bind the generator to Laravel’s container for dependency injection:

    $this->app->singleton(UuidGenerator::class, function ($app) {
        return new UuidGenerator();
    });
    

    Then inject it into services:

    use Illuminate\Support\Facades\App;
    
    $uuid = App::make(UuidGenerator::class)->generate();
    
  2. API Responses: Return UUIDs in JSON APIs:

    return response()->json([
        'data' => [
            'id' => $user->uuid->toString(),
            'name' => $user->name,
        ],
    ]);
    
  3. Event Sourcing: For Broadway, use UUIDs in event metadata:

    $metadata = [
        'uuid' => UuidGenerator::generate()->toString(),
        'timestamp' => now()->toIso8601String(),
    ];
    
  4. Testing Helpers: Create a test trait for reusable UUID assertions:

    trait AssertsUuids
    {
        protected function assertValidUuid($uuid)
        {
            $this->assertInstanceOf(UuidInterface::class, $uuid);
            $this->assertEquals(36, strlen($uuid->toString()));
        }
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • Issue: The package requires PHP 7.2+, but Laravel 9+ uses PHP 8.0+. While compatible, some PHP 8.2+ features (e.g., enums, new attributes) may break.
    • Fix: Test thoroughly or fork the package for PHP 8.2+ support.
  2. Broadway-Specific Assumptions:

    • Issue: The package is designed for Broadway’s event-sourcing patterns. Non-Broadway use may miss features like message ID generation.
    • Fix: Use ramsey/uuid directly if you need broader UUID functionality.
  3. UUID Format Inconsistencies:

    • Issue: Mixing broadway/uuid-generator with Laravel’s Str::uuid() or symfony/uuid can cause format mismatches (e.g., hyphenated vs. non-hyphenated).
    • Fix: Standardize on one library for UUID generation across the app.
  4. Database Schema Conflicts:

    • Issue: UUID columns may not be supported in older databases (e.g., MySQL < 8.0).
    • Fix: Use string columns with a fixed length (36 chars) and validate UUID format in the application layer.
  5. Testing Determinism:

    • Issue: UuidGenerator::generate() may produce different UUIDs across test runs unless seeded.
    • Fix: Use a fixed seed or mock the generator in tests:
      $this->app->instance(UuidGenerator::class, $mockUuidGenerator);
      

Debugging Tips

  1. UUID Validation: Use ramsey/uuid's validator to check UUIDs:

    use Ramsey\Uuid\Validator;
    
    $validator = new Validator();
    $isValid = $validator->validate($uuidString);
    
  2. Performance Bottlenecks:

    • UUID generation is lightweight, but bulk operations (e.g., creating 10K records) may benefit from batching.
    • Tip: Pre-generate UUIDs in memory if performance is critical.
  3. Serialization Issues:

    • Issue: UUID objects may not serialize/deserialize cleanly (e.g., in queues or cache).
    • Fix: Store UUIDs as strings and convert back when needed:
      $uuidString = $uuid->toString();
      $uuid = Uuid::fromString($uuidString);
      

Extension Points

  1. Custom UUID Generators: Extend the package to support non-random UUIDs (e.g., time-based, hash-based):

    use Ramsey\Uuid\Uuid;
    
    $timeBasedUuid = Uuid::uuid1(); // Time-based UUID
    
  2. Laravel Service Provider: Create a custom provider to override UUID generation:

    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Broadway\UuidGenerator\UuidGenerator;
    
    class UuidServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(UuidGenerator::class, function ($app) {
                return new CustomUuidGenerator(); // Your implementation
            });
        }
    }
    
  3. Testing Utilities: Add helper methods to your test suite:

    // In a TestCase or trait
    protected function generateTestUuid(): string
    {
        return UuidGenerator::generate()->toString();
    }
    

Configuration Quirks

  1. Ramsey UUID Version:

    • The package depends on ramsey/uuid v4.x. If you update ramsey/uuid, ensure compatibility:
      composer require ramsey/uuid:^4.0
      
  2. Strict Types:

    • The package uses strict types (PHP 7.4+). If your project uses loose typing, add:
      declare(strict_types=1);
      
      to files using the package.
  3. Binary UUIDs:

    • The package includes a binary UUID converter (from v0.3.0). Use it for compact storage:
      $binaryUuid = UuidGenerator::generate()->getBytes();
      

Best Practices

  1. Immutable UUIDs: Treat UUIDs as immutable identifiers. Avoid regenerating them after creation.

  2. Indexing: Ensure UUID columns are indexed in databases for performance:

    $table->uuid('uuid')->primary();
    $
    
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.
terminal42/code-quality-tools
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