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 component offers an object-oriented API to generate and work with unique identifiers. Includes ULIDs and UUIDs (v1 and v3–v8), with implementations compatible with both 32-bit and 64-bit systems for consistent, portable IDs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require symfony/uid
    
  2. Generate a UUID (v7 by default):
    use Symfony\Uid\Uuid;
    use Symfony\Uid\UuidFactory;
    
    $factory = UuidFactory::v7();
    $uuid = $factory->create(); // e.g., "018d4f98-7f3b-7e4c-8d4f-987f3b7e4c8d"
    
  3. Generate a ULID:
    use Symfony\Uid\Ulid;
    
    $ulid = Ulid::generate(); // e.g., "01H5Z3X9X9X9X9X9X9X9X9X9X9"
    

First Use Case: Database Model IDs

Replace Laravel’s default auto-increment IDs with UUIDs in a model:

use Illuminate\Database\Eloquent\Model;
use Symfony\Uid\Uuid;
use Symfony\Uid\UuidFactory;

class Post extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->{$model->getKeyName()} = UuidFactory::v7()->create();
        });
    }
}

Key Classes to Know

Class Purpose
UuidFactory Factory for generating UUIDs (v1, v3–v8). Defaults to v7.
Ulid Generates ULIDs (Universally Unique Lexicographically Sortable IDs).
AbstractUid Base class for all UIDs (UUIDs/ULIDs). Provides validation, formatting.
MockUuidFactory For deterministic UUIDs in tests (e.g., MockUuidFactory::fromString()).

Implementation Patterns

1. UUID Generation Strategies

Time-Ordered IDs (UUIDv7)

Use for analytics, event sourcing, or time-window queries:

$factory = UuidFactory::v7();
$uuid = $factory->create(); // e.g., "018d4f98-7f3b-7e4c-8d4f-987f3b7e4c8d"
  • Pros: Time-ordered, sortable, no collisions.
  • Use Case: Logs, transactions, or any data needing chronological sorting.

Random IDs (UUIDv4)

Use for privacy-sensitive data (e.g., user IDs):

$uuid = Uuid::v4(); // e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  • Pros: No time/entropy exposure.
  • Use Case: User accounts, tokens, or PII.

Namespace-Based IDs (UUIDv3/v5)

Use for deterministic IDs from namespaces (e.g., URLs, DNS):

$factory = UuidFactory::v5('6ba7b810-9dad-11d1-80b4-00c04fd430c8'); // DNS namespace
$uuid = $factory->create('example.com'); // e.g., "d3b07384-435f-5396-8554-039c2ffa8f69"
  • Pros: Reproducible for the same input.
  • Use Case: Caching keys, content hashing.

2. ULID for Lexicographical Sorting

$ulid = Ulid::generate(); // e.g., "01H5Z3X9X9X9X9X9X9X9X9X9X9"
  • Pros: Sortable by generation time, shorter than UUIDs (26 chars vs. 36).
  • Use Case: Time-series data, logs, or any ordered dataset.

3. Database Integration

PostgreSQL/MySQL 8.0+ (Recommended)

// Schema migration
Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary(); // or ->binary(16) for UUIDs
    $table->string('title');
    $table->timestamps();
});
  • Binary Storage: Use binary(16) for UUIDs to save space and improve performance:
    $table->binary('id')->primary();
    

Legacy Databases

For MySQL <8.0 or Oracle, use char(36):

$table->char('id', 36)->primary();

4. Validation and Serialization

use Symfony\Uid\Uuid;

// Validate a string
if (Uuid::isValid($string)) {
    $uuid = Uuid::fromString($string);
}

// Serialize to different formats
$uuid = Uuid::v4();
echo $uuid->toRfc9562(); // "018d4f987f3b7e4c8d4f987f3b7e4c8d"
echo $uuid->toBase58();   // "2J..." (URL-safe)
echo $uuid->toBinary();  // Binary string for storage

5. Testing with Deterministic UUIDs

use Symfony\Uid\MockUuidFactory;

$factory = MockUuidFactory::fromString('018d4f98-7f3b-7e4c-8d4f-987f3b7e4c8d');
$uuid = $factory->create(); // Always returns the same UUID
  • Use Case: Reproducible tests for time-sensitive workflows (e.g., "create order at timestamp X").

6. Laravel Service Provider Integration

Register a global UUID factory in AppServiceProvider:

use Symfony\Uid\UuidFactory;

public function register()
{
    $this->app->singleton('uuid.factory', function () {
        return UuidFactory::v7();
    });
}

Then inject it into controllers/services:

use Illuminate\Support\Facades\App;

class PostController extends Controller
{
    public function store()
    {
        $uuid = App::make('uuid.factory')->create();
        // ...
    }
}

7. API Responses and URLs

Use BASE_58 for compact, URL-safe IDs:

use Symfony\Uid\Uuid;

$uuid = Uuid::v4();
$shortUrl = route('post.show', ['id' => $uuid->toBase58()]);
  • Example Output: /post/2J... (vs. /post/6ba7b810-9dad-11d1-80b4-00c04fd430c8).

8. Event Sourcing/Audit Logs

Use UUIDv7 for time-ordered events:

use Symfony\Uid\UuidFactory;

class OrderCreated implements ShouldBeStored
{
    public function __construct(
        public string $orderId,
        public string $userId,
        public array $items
    ) {}

    public static function create(array $data): self
    {
        return new self(
            orderId: UuidFactory::v7()->create(),
            userId: $data['user_id'],
            items: $data['items']
        );
    }
}

Gotchas and Tips

Pitfalls

  1. UUIDv1 Time Dependence

    • UUIDv1 includes the current time, which can cause issues in distributed systems with clock skew.
    • Fix: Use UUIDv7 (time-ordered but optimized for x64) or Ulid instead.
  2. Binary Storage in MySQL <8.0

    • MySQL <8.0 doesn’t support BINARY(16) for UUIDs. Use CHAR(36) instead.
    • Fix: Upgrade MySQL or use CHAR(36) with a custom accessor:
      protected $casts = [
          'id' => 'string',
      ];
      
  3. ULID vs. UUID Sorting

    • ULIDs are lexicographically sortable by time, but UUIDv7 is also time-ordered.
    • Tip: Use Ulid if you need shorter strings (26 chars) or UUIDv7 if you need RFC compliance.
  4. MockUuidFactory in Production

    • MockUuidFactory is for testing only. Never use it in production.
    • Fix: Use UuidFactory::v7() or Ulid::generate() in production.
  5. Case Sensitivity in UUIDs

    • UUIDs are case-insensitive, but UUIDv1 defaults to lowercase in Symfony/UID.
    • Tip: Normalize case when comparing or storing UUIDs:
      $uuid->toRfc
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai