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.
## 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 generationStr::isUuid($value) – Validate UUID formatHasUuids trait – Auto-replace integer PKs with UUID stringsBinaryUuidMigrations – Database-optimized migration helpersPublish 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
}
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;
}
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
// 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
// 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();
});
use Illuminate\Validation\Rules\Uuid;
$request->validate([
'user_id' => ['required', new Uuid],
]);
// 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');
}
// Convert to SQL Server format
$sqlServerGuid = Str::uuidToSqlServer($uuid);
// Convert back
$uuid = Str::sqlServerBinaryToUuid($sqlServerGuid);
// Binary format for uniqueidentifier columns
$sqlServerBinary = Str::uuidToSqlServerBinary($uuid);
// 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),
]);
// 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);
// String to binary
$binary = Str::uuidToBinary($uuid);
// Binary to string
$string = Str::binaryToUuid($binary);
Binary UUID Serialization Issues
return response()->json(['id' => (string) $model->id]);
SQL Server Byte Order Problems
Str::uuidToSqlServer() and Str::sqlServerBinaryToUuid()
$sqlGuid = Str::uuidToSqlServer($uuid);
$convertedBack = Str::sqlServerBinaryToUuid($sqlGuid);
Route Binding Failures
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}');
Foreign Key Type Mismatches
// If parent uses binary UUID
$table->binary('parent_id')->foreign('id')->references('id');
Performance in Loops
Str::fastUuid() or batch generation:
$uuids = array_map(fn() => Str::fastUuid(), range(1, 1000));
Case Sensitivity in Comparisons
if (strtolower($uuid1) === strtolower($uuid2)) { ... }
SQLite Limitations
$table->string('id')->unique();
Verify UUID Generation
$uuid = Str::uuid();
var_dump(Str::isUuid($uuid)); // Should return true
var_dump(Str::isSqlServerGuid($uuid)); // For SQL Server
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
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)'
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
Check UUID Version
$uuid = Str::timeBasedUuid();
var_dump(Str::isTimeBasedUuid($uuid)); // Should return true
binary(16) columnsHow can I help you explore Laravel packages today?