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 for RFC 4122 and RFC 9562. Create UUID v1/3/4/5/6/7/8, nil UUIDs, import and validate strings, compare UUIDs, and access string/hex/bytes/URN/version/variant/time properties.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require webpatser/uuid
    

    No additional configuration required—works out-of-the-box with PHP 8.5+.

  2. First Use Case: Replace Laravel’s default auto-increment IDs with UUIDs for a model:

    use Webpatser\Uuid\Uuid;
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model
    {
        protected $keyType = 'string';
        protected $primaryKey = 'id';
    
        protected static function boot()
        {
            parent::boot();
    
            static::creating(function ($model) {
                $model->{$model->primaryKey} = Uuid::v7()->string;
            });
        }
    }
    
  3. Validation: Add a UUID validation rule in Laravel’s app/Providers/AppServiceProvider.php:

    use Illuminate\Support\Facades\Validator;
    use Webpatser\Uuid\Uuid;
    
    Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
        return Uuid::validate($value);
    });
    

Where to Look First

  • README.md: Quick-start examples for UUID generation (v4, v7, etc.).
  • API Reference: Focus on Uuid::v7() for databases and Uuid::v4() for general use.
  • SQL Server Support: Use Uuid::importFromSqlServer() if migrating from SQL Server GUIDs.

Implementation Patterns

Workflows

1. Database Model Integration

  • UUIDv7 for Time-Ordered IDs:
    class Post extends Model
    {
        protected $keyType = 'string';
        protected $primaryKey = 'id';
    
        protected static function boot()
        {
            parent::boot();
            static::creating(function ($model) {
                $model->id = Uuid::v7()->string; // Monotonic for databases
            });
        }
    }
    
  • UUIDv4 for Auth Tokens:
    $token = Uuid::v4()->string; // Cryptographically secure
    

2. Laravel Validation

Extend Laravel’s validation with UUID rules:

use Illuminate\Support\Facades\Validator;
use Webpatser\Uuid\Uuid;

Validator::extend('valid_uuid', function ($attribute, $value, $parameters) {
    return Uuid::validate($value);
});

// Usage in Form Requests:
$this->validate($request, [
    'external_id' => 'required|valid_uuid',
]);

3. API Key Generation

Generate and store UUIDv4 keys in a api_keys table:

$key = Uuid::v4();
ApiKey::create([
    'key' => $key->string,
    'expires_at' => now()->addYear(),
]);

4. SQL Server Compatibility

Import/export UUIDs for SQL Server:

// Import from SQL Server GUID
$uuid = Uuid::importFromSqlServer($sqlGuidString);

// Export to SQL Server format
$sqlGuid = $uuid->toSqlServer();

5. Name-Based UUIDs (v3/v5)

Generate deterministic UUIDs for external resources:

$dnsUuid = Uuid::generate(5, 'example.com', Uuid::NS_DNS);

Integration Tips

  • Laravel Eloquent: Use protected $keyType = 'string' and override boot() to auto-generate UUIDs.
  • Database Indexing: For UUIDv7, ensure your database supports UUID or BINARY(16) types (PostgreSQL, MySQL 8.0+, SQL Server).
  • Caching: Cache UUID generation for high-throughput APIs (e.g., Uuid::v4() in a singleton).
  • Testing: Mock UUID generation in tests:
    $this->partialMock(Uuid::class, function ($mock) {
        $mock->shouldReceive('v4')->andReturn(Uuid::import('550e8400-e29b-41d4-a716-446655440000'));
    });
    

Gotchas and Tips

Pitfalls

  1. PHP 8.5 Requirement:

    • Error: Class 'Webpatser\Uuid\Uuid' not found if using PHP <8.5.
    • Fix: Upgrade PHP or use ramsey/uuid as an alternative.
  2. UUIDv1 MAC Address Dependency:

    • Gotcha: UUIDv1 uses MAC addresses, which may cause issues in cloud environments (e.g., AWS Lambda).
    • Solution: Prefer UUIDv7 for databases or UUIDv4 for general use.
  3. SQL Server Endianness:

    • Gotcha: SQL Server stores GUIDs with mixed endianness. Manual conversion is error-prone.
    • Fix: Use Uuid::importFromSqlServer() and toSqlServer() methods.
  4. Nil UUID Handling:

    • Gotcha: Nil UUIDs (all zeros) may cause issues in queries or comparisons.
    • Fix: Validate with Uuid::isNilUuid($uuid) before use.
  5. UUIDv7 Time Precision:

    • Gotcha: UUIDv7 uses Unix timestamps with sub-millisecond precision, which may not align with your database’s timezone.
    • Fix: Store timestamps separately if timezone handling is critical.

Debugging

  • Invalid UUIDs: Use Uuid::validate($uuid) to check format before processing.

    if (!Uuid::validate($request->input('uuid'))) {
        throw new \InvalidArgumentException('Invalid UUID format.');
    }
    
  • Performance Bottlenecks: Benchmark UUID generation with Uuid::benchmark(10000, 7) to identify slowdowns.

  • SQL Server Issues: If UUIDs appear corrupted after import/export, verify byte order:

    $uuid = Uuid::importFromSqlServer($sqlGuid);
    $binary = $uuid->toSqlServerBinary(); // Debug binary output
    

Config Quirks

  • No Configuration File: The package is stateless—no config/uuid.php exists. All settings are runtime.

  • Default Namespace for Name-Based UUIDs: Use predefined namespaces (e.g., Uuid::NS_DNS) for consistency:

    $uuid = Uuid::generate(5, 'user@example.com', Uuid::NS_DNS);
    

Extension Points

  1. Custom UUID Versions: Extend the library by implementing a new version (e.g., UUIDv8) in a trait:

    trait CustomUuidVersion
    {
        public static function v8(): Uuid
        {
            // Custom logic for UUIDv8
        }
    }
    
  2. Laravel Service Provider: Bind the UUID generator to Laravel’s container for dependency injection:

    $this->app->bind(Uuid::class, function () {
        return new Uuid();
    });
    
  3. Database Casting: Create a custom Eloquent cast for UUIDs:

    use Webpatser\Uuid\Uuid;
    
    class UuidCast implements AttributeCast
    {
        public function get($model, string $key, $value, array $attributes)
        {
            return Uuid::import($value);
        }
    
        public function set($model, string $key, $value, array $attributes)
        {
            return $value->string;
        }
    }
    
  4. Benchmarking: Use the built-in benchmarking to compare versions:

    $result = Uuid::benchmark(10000, 7);
    // Log or store results for performance tracking.
    

Pro Tips

  • UUIDv7 for Databases: UUIDv7’s time-ordered nature improves indexing in distributed systems. Use it for primary keys in PostgreSQL/MySQL 8.0+.

  • UUIDv4 for Security: Always use Uuid::v4() for sensitive identifiers (e.g., tokens, API keys) due to its cryptographic randomness.

  • SQL Server Optimization: For bulk inserts, convert UUIDs to binary format before saving:

    $uuid->toSqlServerBinary(); // Faster than string storage
    
  • Laravel Scout: If using UUIDs with Scout, cast to strings for searchability:

    $searchable = [
        'id' => function () {
            return $this->id; // Ensure this is a string
        },
    ];
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport