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

ramsey/uuid

Generate and work with UUIDs in PHP using ramsey/uuid. Create v1, v4, and other UUID types, parse and validate UUID strings, and integrate easily via Composer. Well-documented, widely used, and standards-aware for reliable identifiers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ramsey/uuid
    

    Add to composer.json if needed:

    "require": {
        "ramsey/uuid": "^4.9"
    }
    
  2. First Use Case: Generate a UUIDv4 (random) in a Laravel controller:

    use Ramsey\Uuid\Uuid;
    use Ramsey\Uuid\Exception\InvalidArgumentException;
    
    $uuid = Uuid::uuid4();
    return response()->json(['uuid' => $uuid->toString()]);
    
  3. Where to Look First:

    • Official Documentation (API reference, RFC details)
    • Uuid facade class (core methods)
    • UuidFactory for custom generators

Implementation Patterns

Core Workflows

1. UUID Generation

  • Random UUIDs (v4):
    $uuid = Uuid::uuid4(); // Default
    $uuid->toString(); // "123e4567-e89b-12d3-a456-426614174000"
    
  • Time-based UUIDs (v6/v7):
    $uuid = Uuid::uuid6(); // RFC 9562 (ordered time)
    $uuid = Uuid::uuid7(); // Unix epoch time (monotonic)
    
  • Custom Generators:
    $generator = Uuid::getFactory()->makeCombGenerator();
    $uuid = $generator->generate();
    

2. Parsing and Validation

  • From string/hex/bytes:
    $uuid = Uuid::fromString('123e4567-e89b-12d3-a456-426614174000');
    $uuid = Uuid::fromHexadecimal('123e4567e89b12d3a456426614174000');
    $uuid = Uuid::fromBytes(\hex2bin('123e4567e89b12d3a456426614174000'));
    
  • Validation:
    if (Uuid::isValid('123e4567-e89b-12d3-a456-426614174000')) {
        $uuid = Uuid::fromString('123e4567-e89b-12d3-a456-426614174000');
    }
    

3. Database Integration

  • Eloquent Model:
    use Illuminate\Database\Eloquent\Model;
    use Ramsey\Uuid\UuidInterface;
    
    class Post extends Model {
        protected $keyType = 'string';
        public $incrementing = false;
        protected $casts = ['id' => UuidInterface::class];
    
        protected static function boot() {
            parent::boot();
            static::creating(function ($model) {
                $model->{$model->getKeyName()} = Uuid::uuid4();
            });
        }
    }
    
  • Migrations:
    Schema::create('posts', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('title');
        $table->timestamps();
    });
    

4. API Responses

  • JSON serialization (built-in):
    return response()->json(['id' => $uuid]); // Auto-converts to string
    
  • Custom serialization:
    $uuid->toString(); // Standard string
    $uuid->toHexadecimal(); // Compact hex
    $uuid->getBytes(); // Binary
    

5. Testing

  • Mock UUIDs for tests:
    $mockUuid = Uuid::fromString('00000000-0000-0000-0000-000000000000');
    $this->assertEquals('00000000-0000-0000-0000-000000000000', $mockUuid->toString());
    

Laravel-Specific Patterns

1. Service Provider Binding

// app/Providers/AppServiceProvider.php
public function register() {
    $this->app->bind(UuidInterface::class, function () {
        return Uuid::uuid4();
    });
}

2. Request Validation

// app/Http/Requests/StorePostRequest.php
public function rules() {
    return [
        'id' => 'sometimes|uuid',
        'external_id' => 'nullable|uuid',
    ];
}

3. Query Scopes

// app/Models/Post.php
public function scopeWithUuid($query, $uuid) {
    return $query->where('id', $uuid->toString());
}

4. API Resources

// app/Http/Resources/PostResource.php
public function toArray($request) {
    return [
        'id' => $this->id->toString(),
        'title' => $this->title,
    ];
}

Gotchas and Tips

Pitfalls

  1. Version Confusion:

    • UUIDv4 (random) vs. UUIDv7 (time-based) behave differently in sorting.
    • Fix: Use Uuid::uuid7() for time-ordered IDs (e.g., database primary keys).
  2. Serialization Issues:

    • Older Laravel versions may fail to serialize UUIDs in sessions/cache.
    • Fix: Ensure Uuid implements Stringable (v4.7.4+):
      $uuid->__toString(); // Works in all contexts
      
  3. Database Collisions:

    • UUIDv4 has a 1 in 2122 collision chance, but UUIDv7 (time-based) can collide within the same millisecond.
    • Fix: Use UUIDv6 for ordered time or UUIDv4 for randomness.
  4. Deprecated Methods:

    • Uuid::UUID_TYPE_PEABODY → Use UUID_TYPE_REORDERED_TIME (v6).
    • CombGenerator → Deprecated; use Uuid::uuid7() instead.
  5. PHP 8.5+ Warnings:

    • Explicit (int) casts may trigger warnings.
    • Fix: Update to ramsey/uuid:^4.9.2 for fixes.

Debugging Tips

  1. Invalid UUIDs:

    • Use Uuid::isValid() before parsing:
      if (!Uuid::isValid($input)) {
          throw new \InvalidArgumentException('Invalid UUID format');
      }
      
  2. Version Detection:

    • Check UUID version:
      $uuid->getVersion(); // Returns 4, 6, 7, etc.
      
  3. Binary vs. String:

    • Convert between formats:
      $binary = $uuid->getBytes();
      $hex = $uuid->toHexadecimal();
      $string = $uuid->toString();
      
  4. Performance:

    • UUIDv7 is faster than UUIDv4 for generation (uses microtime()).
    • UUIDv6 is slower (requires MAC address lookup).

Extension Points

  1. Custom Codecs:

    • Implement CodecInterface for custom encoding:
      class CustomCodec implements CodecInterface {
          public function encode(UuidInterface $uuid): string { ... }
          public function decode(string $string): UuidInterface { ... }
      }
      
  2. UUID Generators:

    • Extend AbstractGenerator for custom logic:
      class CustomGenerator extends AbstractGenerator {
          protected function generate(): UuidInterface {
              return Uuid::fromString('custom-' . Uuid::uuid4());
          }
      }
      
  3. Laravel Observers:

    • Auto-generate UUIDs on model creation:
      class PostObserver {
          public function creating(Post $post) {
              $post->id = Uuid::uuid4();
          }
      }
      
  4. API Middleware:

    • Validate UUIDs in requests:
      public function handle($request, Closure $next) {
          if ($request->has('id') && !Uuid::isValid($request->id)) {
              throw new \InvalidArgumentException('Invalid UUID');
          }
          return $next($request);
      }
      

Configuration Quirks

  1. Randomness:
    • UUIDv4 uses PHP’s random_bytes() (secure by default).
    • For non-secure
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle