webpatser/laravel-uuid
Laravel package for generating and working with UUIDs. Provides a UUID model trait, helpers to create v1/v4 UUIDs, and integrates with Eloquent so models can use UUID primary keys instead of auto-increment IDs.
Installation:
composer require webpatser/laravel-uuid
First Use Case: Generate a UUID in a controller or model:
use Illuminate\Support\Str;
$uuid = Str::uuid(); // Standard RFC 4122 v4
$uuid = Str::fastUuid(); // 15% faster alternative
$uuid = Str::timeBasedUuid(); // RFC 4122 v1 (time-based)
Database Column Setup: Use the migration helper for binary UUIDs (recommended for MySQL/PostgreSQL):
use Webpatser\LaravelUuid\BinaryUuidMigrations;
Schema::create('users', function (Blueprint $table) {
BinaryUuidMigrations::uuid($table); // Auto-detects database type
$table->string('name');
$table->timestamps();
});
Model Integration:
Add the HasBinaryUuids trait to your Eloquent model:
use Webpatser\LaravelUuid\HasBinaryUuids;
class User extends Model
{
use HasBinaryUuids;
// Automatically casts binary UUID to string for APIs
}
| Use Case | Method | Notes |
|---|---|---|
| General-purpose UUID | Str::uuid() |
RFC 4122 v4 (random) |
| Time-based UUID | Str::timeBasedUuid() |
RFC 4122 v1 (time + MAC address) |
| Fast generation | Str::fastUuid() |
15% faster than Str::uuid() |
| Name-based UUID | Str::nameUuidSha1('name') |
RFC 4122 v5 (deterministic) |
| SQL Server GUID | Str::uuidToSqlServer($uuid) |
Converts to uniqueidentifier format |
Example: Multi-Version UUID Generation
$versions = [
'v1' => Str::timeBasedUuid(),
'v4' => Str::uuid(),
'v5' => Str::nameUuidSha1('user@example.com'),
];
Binary UUID Migrations (Recommended for MySQL/PostgreSQL):
use Webpatser\LaravelUuid\BinaryUuidMigrations;
Schema::create('orders', function (Blueprint $table) {
BinaryUuidMigrations::uuid($table); // Creates `uuid` column as binary(16)
$table->foreignId('user_id')->constrained();
$table->timestamps();
});
SQL Server-Specific Handling:
// Convert standard UUID to SQL Server GUID
$sqlServerGuid = Str::uuidToSqlServer($uuid);
// Convert SQL Server binary GUID back to UUID
$uuid = Str::sqlServerBinaryToUuid($binaryGuid);
SQLite Fallback:
// SQLite doesn't support binary UUIDs; use string storage
$table->uuid('id')->default(Str::uuid());
Route Model Binding:
// routes/web.php
Route::get('/users/{user}', [UserController::class, 'show']);
// UserController.php
public function show(User $user) {
// $user->id is automatically cast to string
}
Foreign Key Relationships:
class Order extends Model
{
use HasBinaryUuids;
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
Polymorphic Relationships:
$model->morphTo(); // Works with UUID primary keys
Validation:
use Illuminate\Validation\Rule;
$validated = Validator::make($request->all(), [
'uuid' => ['required', 'uuid'],
'custom_uuid' => [Rule::uuid()],
]);
API Response Casting:
// In AppServiceProvider::boot()
Model::shouldBeCastToType('string', 'uuid');
Manual Casting:
return response()->json([
'user_id' => (string) $user->id, // Ensures string output
]);
Fast UUID Generation for Seeders:
public function run()
{
$uuids = Str::fastUuid()->make(1000); // Generates 1000 UUIDs in bulk
User::insert([
'id' => $uuids,
'name' => 'Test User',
]);
}
Batch Insertion with Binary UUIDs:
DB::table('users')->insert([
'id' => Str::fastUuid()->make(1000),
'name' => 'Batch User',
]);
Leverage Str Macros Globally:
Add custom UUID methods to app/Providers/AppServiceProvider.php:
Str::macro('orderedUuid', function () {
return Str::uuid()->toRfc4122();
});
Database-Specific Config: Use environment variables to toggle binary UUIDs:
// config/uuid.php
return [
'use_binary' => env('DB_CONNECTION') !== 'sqlite',
];
Testing UUIDs:
Use Str::fakeUuid() for deterministic testing:
$uuid = Str::fakeUuid('550e8400-e29b-41d4-a716-446655440000');
Legacy System Migration:
Str::isUuid() to validate existing IDs.uuid column alongside id during transition:
$table->id();
$table->uuid('uuid')->unique()->default(Str::uuid());
Binary UUID Serialization:
\Webpatser\Uuid\Uuid in JSON APIs.protected $casts = ['id' => 'string'];
SQL Server Byte Order:
Str::uuidToSqlServer() for inserts and Str::sqlServerBinaryToUuid() for retrievals.SQLite Limitations:
Str::uuid() directly and avoid binary migrations:
$table->string('id')->default(Str::uuid());
UUIDv1 Time Dependence:
Str::timeBasedUuid() includes MAC address, causing issues in serverless environments.Str::uuid() (v4) for stateless deployments or mock the MAC address in tests.Route Model Binding Quirks:
HasBinaryUuids and cast id to string:
protected $casts = ['id' => 'string'];
Foreign Key Constraints:
BinaryUuidMigrations for consistent column types:
$table->binaryUuid('user_id'); // Explicit binary UUID FK
UUID Validation Errors:
Str::isUuid($value) to validate manually:
if (!Str::isUuid($request->uuid)) {
throw ValidationException::withMessages(['uuid' => 'Invalid UUID format.']);
}
Binary UUID Storage Issues:
Schema::getColumnListing('users'); // Should show 'uuid' as binary(16)
SQL Server GUID Problems:
$binary = Str::uuidToSqlServerBinary($uuid);
$uuidBack = Str::sqlServerBinaryToUuid($binary);
dd($uuid === $uuidBack); // Should be true
Performance Bottlenecks:
Str::uuid() vs. Str::fastUuid():
$time = microtime(true);
for ($i = 0; $i < 1000; $i++) {
$uuid = Str::fastUuid();
}
echo microtime(true) - $
How can I help you explore Laravel packages today?