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

rhumsaa/uuid

Deprecated PHP 5.3+ library for generating and working with RFC 4122 UUIDs (v1, v3, v4, v5). No longer maintained—use ramsey/uuid instead.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the successor package (since this is archived):
    composer require ramsey/uuid
    
  2. Basic UUID generation in Laravel:
    use Ramsey\Uuid\Uuid;
    
    $uuid = Uuid::uuid4(); // Random UUID (v4)
    $uuidString = $uuid->toString();
    
  3. First use case: Store UUIDs in a database or use them as primary keys in Eloquent models.

Where to Look First

  • API Documentation (for ramsey/uuid).
  • Laravel Integration: Use ramsey/uuid's Doctrine\DBAL\Types\UuidType for database columns (if needed).
  • Common Methods:
    • Uuid::uuid1() (time-based),
    • Uuid::uuid4() (random),
    • Uuid::uuid5(Uuid::NAMESPACE_DNS, 'domain.com') (namespace-based).

Implementation Patterns

Core Workflows

1. UUID as Primary Key in Eloquent

use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;

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

    protected static function boot() {
        parent::boot();
        static::creating(function ($model) {
            $model->{$model->primaryKey} = Uuid::uuid4()->toString();
        });
    }
}
  • Tip: Use $keyType = 'string' and $incrementing = false to disable auto-increment.

2. Database Column Setup (PostgreSQL/MySQL)

// PostgreSQL (recommended)
Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->timestamps();
});

// MySQL (requires UUID extension or `char(36)` fallback)
Schema::create('posts', function (Blueprint $table) {
    $table->char('id', 36)->primary();
    $table->string('title');
    $table->timestamps();
});

3. API Responses

return response()->json([
    'data' => [
        'id' => $post->id, // UUID string
        'title' => $post->title,
    ]
]);
  • Validation: Use Laravel's Uuid validator:
    use Illuminate\Validation\Rule;
    
    $request->validate([
        'id' => ['required', 'uuid'],
    ]);
    

4. Namespace-Based UUIDs (v3/v5)

// Version 5 UUID for a DNS namespace (e.g., 'example.com')
$uuid = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com');
  • Use Case: Generate deterministic UUIDs for URLs, domains, or external identifiers.

5. Doctrine DBAL Integration (Legacy)

use Ramsey\Uuid\Doctrine\UuidType;

// In a migration (if using Doctrine outside Laravel)
$table->addColumn('id', UuidType::UUID_TYPE);

Integration Tips

  • Caching: Cache UUIDs in Redis if generating high volumes (e.g., for API keys).
  • Testing: Use Uuid::uuid4() for predictable test IDs (e.g., Uuid::fromString('550e8400-e29b-41d4-a716-446655440000')).
  • Migration: Replace rhumsaa/uuid with ramsey/uuid via:
    composer require ramsey/uuid --update-with-dependencies
    
    • No code changes are needed; APIs are identical.

Gotchas and Tips

Pitfalls

  1. 32-bit PHP Limitations:

    • Methods like getMostSignificantBits() may throw UnsatisfiedDependencyException on 32-bit systems.
    • Workaround: Use ramsey/uuid (which handles this better) or ensure 64-bit PHP.
  2. UUIDv1 Time Dependence:

    • Version 1 UUIDs include a timestamp. If your system clock is incorrect, UUIDs may appear out of order.
    • Tip: Use Uuid::uuid4() for randomness or Uuid::uuid5() for deterministic IDs.
  3. Doctrine Integration:

    • The Doctrine\UuidType is deprecated in favor of native database UUID types (PostgreSQL/MySQL 8.0+).
    • Tip: Use Schema::uuid() in Laravel migrations instead.
  4. Performance:

    • Version 4 UUIDs are slower than auto-increment IDs in MySQL (due to string comparisons).
    • Tip: Use UUIDs for distributed systems; reserve auto-increment for single-database apps.
  5. Validation Quirks:

    • Uuid::isValid() may return false for UUIDs with uppercase letters (e.g., "550E8400-E29B-41D4-A716-446655440000").
    • Fix: Normalize strings with strtolower() before validation.

Debugging

  • Invalid UUIDs: Use Uuid::isValid($string) to validate manually.
  • Database Errors: Ensure your database supports UUIDs (PostgreSQL: uuid-ossp extension; MySQL: UUID() function or char(36)).
  • Clock Skew: For UUIDv1, verify system time with date('c').

Extension Points

  1. Custom UUID Namespaces:
    $customNamespace = Uuid::NAMESPACE_URL; // or define your own
    $uuid = Uuid::uuid5($customNamespace, 'https://example.com/resource');
    
  2. Binary UUIDs:
    $binaryUuid = Uuid::uuid4()->getBytes(); // Raw binary format
    
  3. Laravel Service Provider:
    // config/uuid.php
    return [
        'default_version' => 'uuid4',
    ];
    
    // AppServiceProvider
    Uuid::setFactory(new \Ramsey\Uuid\Factory\UuidFactory());
    
  4. Event Sourcing:
    • Use UUIDs as event IDs in CQRS/ES architectures for traceability.

Configuration Quirks

  • PostgreSQL: Enable the uuid-ossp extension for gen_random_uuid().
  • MySQL: Use char(36) if UUID support is lacking (store as string).
  • SQLite: Store UUIDs as TEXT (no native UUID type).

Migration Notes

  • From rhumsaa/uuid to ramsey/uuid:
    • Replace use Rhumsaa\Uuid\Uuid; with use Ramsey\Uuid\Uuid;.
    • All methods (uuid1(), uuid4(), etc.) remain unchanged.
  • Database Schema:
    • Update migrations to use uuid() (PostgreSQL) or char(36) (MySQL/SQLite).
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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