webpatser/uuid
Pure PHP UUID generator/validator for RFC 4122 and RFC 9562. Create UUID v1/3/4/5/6/7/8, nil UUIDs, import and validate strings, compare UUIDs, and access string/hex/bytes/URN/version/variant/time properties.
Installation:
composer require webpatser/uuid
No additional configuration required—works out-of-the-box with PHP 8.5+.
First Use Case: Replace Laravel’s default auto-increment IDs with UUIDs for a model:
use Webpatser\Uuid\Uuid;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $keyType = 'string';
protected $primaryKey = 'id';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->primaryKey} = Uuid::v7()->string;
});
}
}
Validation:
Add a UUID validation rule in Laravel’s app/Providers/AppServiceProvider.php:
use Illuminate\Support\Facades\Validator;
use Webpatser\Uuid\Uuid;
Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
return Uuid::validate($value);
});
Uuid::v7() for databases and Uuid::v4() for general use.Uuid::importFromSqlServer() if migrating from SQL Server GUIDs.class Post extends Model
{
protected $keyType = 'string';
protected $primaryKey = 'id';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->id = Uuid::v7()->string; // Monotonic for databases
});
}
}
$token = Uuid::v4()->string; // Cryptographically secure
Extend Laravel’s validation with UUID rules:
use Illuminate\Support\Facades\Validator;
use Webpatser\Uuid\Uuid;
Validator::extend('valid_uuid', function ($attribute, $value, $parameters) {
return Uuid::validate($value);
});
// Usage in Form Requests:
$this->validate($request, [
'external_id' => 'required|valid_uuid',
]);
Generate and store UUIDv4 keys in a api_keys table:
$key = Uuid::v4();
ApiKey::create([
'key' => $key->string,
'expires_at' => now()->addYear(),
]);
Import/export UUIDs for SQL Server:
// Import from SQL Server GUID
$uuid = Uuid::importFromSqlServer($sqlGuidString);
// Export to SQL Server format
$sqlGuid = $uuid->toSqlServer();
Generate deterministic UUIDs for external resources:
$dnsUuid = Uuid::generate(5, 'example.com', Uuid::NS_DNS);
protected $keyType = 'string' and override boot() to auto-generate UUIDs.UUID or BINARY(16) types (PostgreSQL, MySQL 8.0+, SQL Server).Uuid::v4() in a singleton).$this->partialMock(Uuid::class, function ($mock) {
$mock->shouldReceive('v4')->andReturn(Uuid::import('550e8400-e29b-41d4-a716-446655440000'));
});
PHP 8.5 Requirement:
Class 'Webpatser\Uuid\Uuid' not found if using PHP <8.5.ramsey/uuid as an alternative.UUIDv1 MAC Address Dependency:
SQL Server Endianness:
Uuid::importFromSqlServer() and toSqlServer() methods.Nil UUID Handling:
Uuid::isNilUuid($uuid) before use.UUIDv7 Time Precision:
Invalid UUIDs:
Use Uuid::validate($uuid) to check format before processing.
if (!Uuid::validate($request->input('uuid'))) {
throw new \InvalidArgumentException('Invalid UUID format.');
}
Performance Bottlenecks:
Benchmark UUID generation with Uuid::benchmark(10000, 7) to identify slowdowns.
SQL Server Issues: If UUIDs appear corrupted after import/export, verify byte order:
$uuid = Uuid::importFromSqlServer($sqlGuid);
$binary = $uuid->toSqlServerBinary(); // Debug binary output
No Configuration File:
The package is stateless—no config/uuid.php exists. All settings are runtime.
Default Namespace for Name-Based UUIDs:
Use predefined namespaces (e.g., Uuid::NS_DNS) for consistency:
$uuid = Uuid::generate(5, 'user@example.com', Uuid::NS_DNS);
Custom UUID Versions: Extend the library by implementing a new version (e.g., UUIDv8) in a trait:
trait CustomUuidVersion
{
public static function v8(): Uuid
{
// Custom logic for UUIDv8
}
}
Laravel Service Provider: Bind the UUID generator to Laravel’s container for dependency injection:
$this->app->bind(Uuid::class, function () {
return new Uuid();
});
Database Casting: Create a custom Eloquent cast for UUIDs:
use Webpatser\Uuid\Uuid;
class UuidCast implements AttributeCast
{
public function get($model, string $key, $value, array $attributes)
{
return Uuid::import($value);
}
public function set($model, string $key, $value, array $attributes)
{
return $value->string;
}
}
Benchmarking: Use the built-in benchmarking to compare versions:
$result = Uuid::benchmark(10000, 7);
// Log or store results for performance tracking.
UUIDv7 for Databases: UUIDv7’s time-ordered nature improves indexing in distributed systems. Use it for primary keys in PostgreSQL/MySQL 8.0+.
UUIDv4 for Security:
Always use Uuid::v4() for sensitive identifiers (e.g., tokens, API keys) due to its cryptographic randomness.
SQL Server Optimization: For bulk inserts, convert UUIDs to binary format before saving:
$uuid->toSqlServerBinary(); // Faster than string storage
Laravel Scout: If using UUIDs with Scout, cast to strings for searchability:
$searchable = [
'id' => function () {
return $this->id; // Ensure this is a string
},
];
How can I help you explore Laravel packages today?