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

Uid Laravel Package

symfony/uid

Symfony UID provides an object-oriented API to generate and represent unique identifiers. Supports ULIDs and UUIDs (v1 and v3–v8) with implementations that work on both 32-bit and 64-bit CPUs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/uid
    

    For Laravel, no additional configuration is needed beyond requiring the package.

  2. First Use Case: Generate a UUIDv7 (time-sortable) in a Laravel controller:

    use Symfony\Uid\Uuid;
    use Symfony\Uid\UuidV7;
    
    // Generate a UUIDv7 (default in Symfony 8+)
    $uid = Uuid::v7();
    $uidString = $uid->toRfc9562(); // e.g., "v7:018a0b1c2d3e4f56..."
    
    // Or explicitly:
    $uid = UuidV7::generate();
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

1. Database Integration (Eloquent Models)

  • Binary Storage (Recommended for Performance):

    use Illuminate\Database\Eloquent\Model;
    use Symfony\Uid\UuidV7;
    
    class Post extends Model
    {
        protected $keyType = 'string';
        public $incrementing = false;
        protected $casts = [
            'id' => 'uuid',
        ];
    
        protected static function boot()
        {
            parent::boot();
            static::creating(function ($model) {
                $model->id = UuidV7::generate()->toBinary();
            });
        }
    }
    
    • Migration:
      Schema::create('posts', function (Blueprint $table) {
          $table->binary('id')->primary(); // Store as binary(16)
          $table->timestamps();
      });
      
  • String Storage (Legacy Systems):

    $table->string('id', 36)->primary(); // CHAR(36) for UUIDv4/v7
    

2. API Responses

  • Serialize UIDs to RFC 9562 (camelCase) or BASE_58 for compactness:
    return response()->json([
        'id' => $post->id->toRfc9562(), // "v7:018a0b1c2d3e4f56..."
        'shareable_id' => $post->id->toBase58(), // "2J...X" (URL-safe)
    ]);
    

3. Validation

  • Validate incoming UIDs (supports binary, base32, base58, RFC 4122, RFC 9562):
    use Symfony\Component\Uid\Uid;
    
    $isValid = Uid::isValid($request->input('id')); // true/false
    

4. Testing with Deterministic UIDs

  • Use MockUuidFactory for reproducible tests:
    use Symfony\Uid\Test\MockUuidFactory;
    use Symfony\Uid\Uuid;
    
    beforeEach(function () {
        Uuid::setFactory(new MockUuidFactory('2023-01-01T00:00:00Z'));
    });
    
    test('generates same UUID for timestamp', function () {
        $uid1 = Uuid::v7();
        $uid2 = Uuid::v7();
        expect($uid1->toString())->toBe($uid2->toString());
    });
    

5. ULID Usage

  • Generate and store ULIDs (time-ordered, lexicographically sortable):
    use Symfony\Uid\Ulid;
    
    $ulid = Ulid::generate();
    $ulidString = $ulid->toString(); // "01H5Z2X3Y4...ABCD"
    

Integration Tips

Laravel Service Providers

  • Bind the UuidFactory interface for dependency injection:
    $this->app->bind(\Symfony\Component\Uid\UuidFactory::class, function () {
        return \Symfony\Component\Uid\Uuid::getFactory();
    });
    

Custom UID Types

  • Extend AbstractUid for domain-specific logic:
    use Symfony\Component\Uid\AbstractUid;
    
    class CustomUid extends AbstractUid
    {
        public static function generate(): static
        {
            return new self(self::generateBytes());
        }
    
        public function toDomainString(): string
        {
            return 'CUST-' . $this->toRfc9562();
        }
    }
    

Database Indexing

  • For PostgreSQL/MySQL 8.0+, use binary storage with indexed columns:
    CREATE INDEX idx_posts_id ON posts (id); -- Works on BINARY(16)
    
  • Avoid CHAR(36) for UUIDs—it’s slower to index and compare.

API Versioning

  • Use toRfc9562() for new APIs (e.g., v7:...) and toRfc4122() for legacy compatibility:
    // API v1 (legacy)
    $uid->toRfc4122(); // "123e4567-e89b-12d3-a456-426614174000"
    
    // API v2 (modern)
    $uid->toRfc9562(); // "v7:018a0b1c2d3e4f56..."
    

Gotchas and Tips

Pitfalls

1. Binary vs. String Storage

  • Binary Storage (BINARY(16)):

    • Pros: Faster indexing, smaller storage, native UUID support in PostgreSQL/MySQL 8.0+.
    • Cons: Harder to debug in logs (use toRfc9562() for readability).
    • Fix: Cast to string in logs:
      \Log::info('UID:', ['id' => $uid->toRfc9562()]);
      
  • String Storage (CHAR(36)):

    • Pros: Human-readable, works in older databases.
    • Cons: Slower queries, larger storage.
    • Fix: Use toBinary() in queries and convert to string only for APIs.

2. UUIDv1 Clock Skew

  • UUIDv1 relies on system time. In distributed systems, clock skew can cause duplicates.
  • Solution: Use UuidV7 (time + randomness) or UuidV4 (random) instead.

3. ULID vs. UUID Sorting

  • ULIDs are lexicographically sortable (e.g., 01H5... < 01H6...).
  • UUIDv7 is time-ordered but requires string comparison (not binary).
  • Tip: Use ULID if you need simple string sorting; UUIDv7 if you need RFC compliance.

4. MockUuidFactory in CI

  • If tests fail intermittently due to time-based UUIDs, ensure MockUuidFactory is set globally:
    // In a test trait or service provider
    Uuid::setFactory(new MockUuidFactory('2023-01-01T00:00:00Z'));
    

5. PHP Version Requirements

  • Symfony 8+: Requires PHP 8.4+ (check composer.json).
  • Symfony 7.4: Requires PHP 8.1+.
  • Fix: Use symfony/uid:^7.4 for PHP 8.1 or ^8.0 for PHP 8.4+.

Debugging Tips

1. Validate UIDs in Logs

  • Add a helper to log UIDs in a readable format:
    if (!Uid::isValid($uidString)) {
        throw new \InvalidArgumentException("Invalid UID: {$uidString}");
    }
    

2. Check UUID Version

  • Debug UUID versions with:
    $uuid = Uid::fromString($id);
    \Log::debug('UUID version:', ['version' => $uuid->getVersion()]);
    

3. Binary Storage Quirks

  • If binary storage causes issues, ensure your database driver supports it:
    • PostgreSQL: Use UUID type or BYTEA.
    • MySQL 8.0+: Use BINARY(16).
    • Legacy MySQL: Use CHAR(36) but accept performance tradeoffs.

4. Time-Based UUIDs in Tests

  • If UuidV7 generates different timestamps in CI vs. local:
    //
    
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