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

Laravel Uuid Laravel Package

webpatser/laravel-uuid

Generate and work with UUIDs in Laravel using the popular ramsey/uuid library. Provides a simple UUID facade and helpers, plus optional model support to use UUID primary keys in Eloquent, making unique IDs easy across apps and services.

View on GitHub
Deep Wiki
Context7
## Getting Started

Install via Composer:
```bash
composer require webpatser/laravel-uuid

First Use Case: Generate a UUID in a controller or service:

use Webpatser\Uuid\Uuid;

$uuid = Uuid::generate(); // Defaults to v4 (random)
return response()->json(['uuid' => $uuid]);

Key Entry Points:

  • Str::uuid() – Laravel Str helper for v4 UUID generation
  • Str::isUuid($value) – Validate UUID format
  • HasUuids trait – Auto-replace integer PKs with UUID strings
  • BinaryUuidMigrations – Database-optimized migration helpers

Publish the config (if needed):

php artisan vendor:publish --provider="Webpatser\Uuid\UuidServiceProvider"

First Migration: Replace integer primary key with UUID:

use Webpatser\Uuid\BinaryUuidMigrations;

Schema::create('users', function (Blueprint $table) {
    BinaryUuidMigrations::uuid($table); // Auto-detects database type
    $table->string('name');
});

First Model: Enable UUID support:

use Webpatser\Uuid\HasUuids;

class User extends Model
{
    use HasUuids; // Auto-replaces integer PK with UUID string
}

Implementation Patterns

1. Model Integration

String UUIDs (Default):

use Webpatser\Uuid\HasUuids;

class User extends Model
{
    use HasUuids; // Auto-replaces integer PK with UUID string

    protected $keyType = 'string';
    public $incrementing = false;
}

Binary UUIDs (Optimized Storage):

use Webpatser\Uuid\HasBinaryUuids;

class User extends Model
{
    use HasBinaryUuids; // Stores as 16-byte binary

    protected $keyType = 'string'; // Still returns string for consistency
    public $incrementing = false;
}

2. Migration Patterns

Auto-Detection (Recommended):

use Webpatser\Uuid\BinaryUuidMigrations;

Schema::create('users', function (Blueprint $table) {
    BinaryUuidMigrations::uuid($table); // Auto-selects column type
    $table->string('name');
});

Manual Column Definitions:

// MySQL/PostgreSQL (binary)
$table->binary('id')->unique();

// SQLite (string)
$table->string('id')->unique();

// SQL Server (uniqueidentifier)
$table->string('id')->unique(); // Handled via Str helpers

3. UUID Generation Strategies

// Random (v4)
Str::uuid();

// Time-based (v1)
Str::timeBasedUuid();

// Deterministic (v5)
Str::nameUuidSha1('namespace', 'user:123');

// High-performance alternatives
Str::fastUuid(); // 15% faster
Str::fastOrderedUuid(); // 25% faster

4. Route Model Binding

// Automatic binding (works out-of-the-box)
Route::get('/users/{user}', function (User $user) {
    return $user;
});

// Custom binding (if needed)
Route::bind('user', function ($value) {
    return User::where('id', $value)->firstOrFail();
});

5. Validation

use Illuminate\Validation\Rules\Uuid;

$request->validate([
    'user_id' => ['required', new Uuid],
]);

6. Foreign Key Relationships

// Binary foreign key
$table->binary('user_id')->foreign('id')->references('id');

// Model relationship
public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id')
                ->setForeignKeyName('user_id');
}

7. SQL Server Specific

// Convert to SQL Server format
$sqlServerGuid = Str::uuidToSqlServer($uuid);

// Convert back
$uuid = Str::sqlServerBinaryToUuid($sqlServerGuid);

// Binary format for uniqueidentifier columns
$sqlServerBinary = Str::uuidToSqlServerBinary($uuid);

8. Bulk Operations

// Generate 1000 UUIDs efficiently
$uuids = array_map(fn() => Str::fastUuid(), range(1, 1000));

// Seed a table with UUIDs
DB::table('users')->insert([
    'id' => $uuids,
    'name' => 'User ' . rand(1, 1000),
]);

9. Custom UUID Versions

// Version 3 (name-based, MD5)
$uuid = Str::nameUuidMd5('namespace', 'user:123');

// Version 6 (reordered time-based)
$uuid = Str::reorderedTimeUuid();

// Version 8 (custom)
$uuid = Str::customUuid(12345678901234567890);

10. UUID Conversion

// String to binary
$binary = Str::uuidToBinary($uuid);

// Binary to string
$string = Str::binaryToUuid($binary);

Gotchas and Tips

Common Pitfalls

  1. Binary UUID Serialization Issues

    • Binary UUIDs may cause problems with JSON APIs or serialization
    • Fix: Cast to string when returning in API responses:
      return response()->json(['id' => (string) $model->id]);
      
  2. SQL Server Byte Order Problems

    • SQL Server uses little-endian while Laravel uses big-endian
    • Fix: Always use Str::uuidToSqlServer() and Str::sqlServerBinaryToUuid()
      $sqlGuid = Str::uuidToSqlServer($uuid);
      $convertedBack = Str::sqlServerBinaryToUuid($sqlGuid);
      
  3. Route Binding Failures

    • UUIDs in routes must match the exact format (hyphens, lowercase)
    • Fix: Use Str::isUuid() validation or normalize input:
      Route::get('/users/{user}', function (User $user) {
          return $user;
      })->where('user', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');
      
  4. Foreign Key Type Mismatches

    • Binary FKs must reference binary PKs (and vice versa)
    • Fix: Ensure consistent UUID types across relationships:
      // If parent uses binary UUID
      $table->binary('parent_id')->foreign('id')->references('id');
      
  5. Performance in Loops

    • Generating UUIDs in tight loops can be slow
    • Fix: Use Str::fastUuid() or batch generation:
      $uuids = array_map(fn() => Str::fastUuid(), range(1, 1000));
      
  6. Case Sensitivity in Comparisons

    • UUIDs are case-insensitive but comparisons may fail
    • Fix: Normalize before comparison:
      if (strtolower($uuid1) === strtolower($uuid2)) { ... }
      
  7. SQLite Limitations

    • SQLite doesn't support binary UUIDs natively
    • Fix: Use string UUIDs with SQLite:
      $table->string('id')->unique();
      

Debugging Techniques

  1. Verify UUID Generation

    $uuid = Str::uuid();
    var_dump(Str::isUuid($uuid)); // Should return true
    var_dump(Str::isSqlServerGuid($uuid)); // For SQL Server
    
  2. Inspect Binary UUIDs

    $binaryId = $model->getKey();
    var_dump(bin2hex($binaryId)); // Should be 32 hex chars (16 bytes)
    var_dump(Str::binaryToUuid($binaryId)); // Convert back to string
    
  3. Check Database Column Types

    $schema = DB::select('SHOW COLUMNS FROM users LIKE "id"');
    var_dump($schema[0]->Type); // Should be 'binary(16)' or 'char(36)'
    
  4. Validate SQL Server GUID Conversion

    $uuid = '550e8400-e29b-41d4-a716-446655440000';
    $sqlGuid = Str::uuidToSqlServer($uuid);
    $convertedBack = Str::sqlServerBinaryToUuid($sqlGuid);
    var_dump($uuid === $convertedBack); // Should be true
    
  5. Check UUID Version

    $uuid = Str::timeBasedUuid();
    var_dump(Str::isTimeBasedUuid($uuid)); // Should return true
    

Pro Tips

  1. Use Binary UUIDs for Production
    • 55% storage savings with binary(16) columns
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