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

webpatser/uuid

Pure PHP UUID generator/validator (RFC 4122 + RFC 9562). Create UUID v1, v3, v4, v5, v6, v7, v8 and nil UUIDs; import, validate, compare, and inspect string/hex/bytes/URN, version, variant, and time fields.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require webpatser/uuid
    

    Add to composer.json under require if using strict versioning.

  2. First Use Case: Replace auto-increment IDs in a Laravel model with UUIDv7 for distributed databases:

    use Webpatser\Uuid\Uuid;
    
    class User extends Model {
        protected $keyType = 'string';
        public $incrementing = false;
        protected $casts = ['id' => Uuid::class];
    
        public static function boot() {
            parent::boot();
            static::creating(function ($model) {
                $model->id = Uuid::v7();
            });
        }
    }
    
  3. Validation: Add a UUID validation rule in Laravel:

    use Webpatser\Uuid\Uuid;
    
    $request->validate([
        'user_id' => ['required', function ($attribute, $value, $fail) {
            if (!Uuid::validate($value)) {
                $fail('The '.$attribute.' must be a valid UUID.');
            }
        }]
    ]);
    

Where to Look First

  • Quick Start: Uuid::v4() (random) or Uuid::v7() (time-ordered) for 90% of use cases.
  • API Reference: Focus on generate(), import(), validate(), and compare() methods.
  • SQL Server Support: Use importFromSqlServer() and toSqlServer() if migrating from legacy systems.
  • Benchmarking: Run php examples/benchmark.php 10000 to compare UUID versions in your environment.

Implementation Patterns

Core Workflows

1. UUID Generation Strategies

Use Case Pattern Example
General-purpose IDs Uuid::v4() $id = Uuid::v4();
Database IDs Uuid::v7() (time-ordered) $id = Uuid::v7();
Deterministic IDs Uuid::generate(5, 'name', NS_DNS) Name-based UUIDs for caching keys.
Legacy Compatibility Uuid::generate(1) Time-based with MAC (avoid for new apps).
SQL Server Uuid::importFromSqlServer() Handle mixed-endianness GUIDs.

2. Laravel Model Integration

use Webpatser\Uuid\Uuid;

class Post extends Model {
    protected $keyType = 'string';
    public $incrementing = false;
    protected $casts = ['id' => Uuid::class];

    protected static function boot() {
        parent::boot();
        static::creating(function ($model) {
            $model->id = Uuid::v7(); // Time-ordered for databases
        });
    }

    public function getRouteKey() {
        return $this->id->string;
    }
}

3. Validation and API Requests

use Webpatser\Uuid\Uuid;

$request->validate([
    'uuid_field' => [
        'required',
        function ($attribute, $value, $fail) {
            if (!Uuid::validate($value)) {
                $fail('Invalid UUID format.');
            }
        }
    ]
]);

// Or use Laravel's built-in UUID cast (if using Laravel 10+)
$request->validate(['uuid_field' => 'uuid']);

4. Database Optimization

  • PostgreSQL/MySQL 8.0+: Use UUIDv7 for time-ordered indexing.
    CREATE INDEX idx_posts_created_at ON posts (id::uuid); -- PostgreSQL
    CREATE INDEX idx_posts_created_at ON posts (HEX(id)); -- MySQL 8.0+
    
  • SQL Server: Use importFromSqlServer() for existing uniqueidentifier columns.
    $sqlGuid = '825B076B-44EC-E511-80DC-00155D0ABC54';
    $uuid = Uuid::importFromSqlServer($sqlGuid);
    

5. Testing UUIDs

use Webpatser\Uuid\Uuid;

public function test_uuid_generation() {
    $uuid = Uuid::v4();
    $this->assertTrue(Uuid::validate($uuid->string));
    $this->assertEquals(4, $uuid->version);
}

public function test_uuid_comparison() {
    $uuid1 = Uuid::v7();
    $uuid2 = Uuid::import($uuid1->string);
    $this->assertTrue(Uuid::compare($uuid1->string, $uuid2->string));
}

6. Performance Benchmarking

// Benchmark UUIDv7 generation (run once per environment)
$result = Uuid::benchmark(10000, 7);
dd($result); // [version, iterations, total_time_ms, avg_time_us, memory_used_bytes, uuids_per_second]

Integration Tips

  1. Laravel Scout: UUIDv7 is searchable but requires string casting. Override toSearchableArray():

    public function toSearchableArray() {
        return [
            'id' => $this->id->string,
            'title' => $this->title,
            // ...
        ];
    }
    
  2. API Keys/Tokens: Use UUIDv4 for cryptographically secure tokens:

    $token = Uuid::v4()->string;
    Cache::put("api_token_{$user->id}", $token, now()->addDays(30));
    
  3. Migration from Incrementing IDs:

    • Add a temporary UUID column during migration.
    • Use a Uuid::generate(8) (custom) for vendor-specific migrations.
    • Backfill UUIDs with a data job:
      User::chunk(1000, function ($users) {
          foreach ($users as $user) {
              $user->uuid = Uuid::v7();
          }
          User::whereIn('id', $users->pluck('id'))->update(['uuid' => \DB::raw('uuid'));
      });
      
  4. Caching Keys: Use UUIDv5 for deterministic cache keys:

    $cacheKey = Uuid::generate(5, "user:{$user->email}", Uuid::NS_DNS)->string;
    Cache::put($cacheKey, $userData, now()->addHours(1));
    
  5. Event Dispatching: Use UUIDv7 for event IDs to ensure chronological ordering:

    event(new UserRegistered(
        userId: Uuid::v7(),
        user: $user
    ));
    

Gotchas and Tips

Pitfalls

  1. PHP 8.5 Requirement:

    • Gotcha: The package requires PHP 8.5+. If your project uses PHP 8.2–8.4, use ramsey/uuid instead.
    • Workaround: None; upgrade PHP or use an alternative.
  2. UUIDv1 MAC Address Dependency:

    • Gotcha: UUIDv1 uses the MAC address, which can cause issues in:
      • Docker/Kubernetes (randomized MACs).
      • CI environments (unpredictable MACs).
      • Multi-tenant SaaS (MAC collisions).
    • Tip: Avoid UUIDv1. Use UUIDv7 for databases or UUIDv4 for general use.
  3. SQL Server Endianness:

    • Gotcha: SQL Server stores GUIDs with mixed endianness. Incorrect handling causes:
      • Duplicate UUIDs when importing.
      • Query failures in joins.
    • Fix: Always use importFromSqlServer() and toSqlServer():
      $uuid = Uuid::importFromSqlServer($sqlGuid); // Correctly converts endianness
      
  4. UUIDv7 Time Precision:

    • Gotcha: UUIDv7 uses a 12-bit sub-millisecond sequence, which may cause:
      • Duplicate UUIDs in high-throughput systems (>100K UUIDs/sec).
      • Time skew in distributed environments.
    • Tip: Benchmark in your environment:
      $result = Uuid::benchmark(100000, 7);
      if ($result['uuids_per_second'] > 100000) {
          // Consider UUIDv4 for high-throughput systems
      }
      
  5. Nil UUID Handling:

    • Gotcha: Uuid::nil() returns a UUID of all zeros (00000000-0000-0000-0000-000000000000).
      • Issue: May conflict with real UUIDs in databases.
      • Tip: Use Uuid::isNilUuid($uuid) to validate before insertion.
  6. Case Sensitivity:

    • Gotcha: UUIDs are case-insensitive, but:
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony