Generate UUID in PHP: Ramsey/UUID and Built-in Methods
Generate UUIDs in PHP using ramsey/uuid and random_bytes(). UUID v4, v7, database column types, Laravel integration, and Doctrine support.
How to Generate UUIDs in PHP
PHP does not include a native UUID function, but you have two excellent options: the ramsey/uuid package (the de facto standard with over 500 million Packagist downloads) and a lightweight approach using random_bytes() that requires no external dependencies.
Using ramsey/uuid (Recommended)
<?php
// Install: composer require ramsey/uuid
use Ramsey\\Uuid\\Uuid;
// Generate UUID v4 (random)
$uuid = Uuid::uuid4();
echo $uuid->toString(); // \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"
// Generate UUID v7 (time-ordered random, new in ramsey/uuid 4.7+)
$uuid7 = Uuid::uuid7();
echo $uuid7->toString(); // Time-sorted, great for database PKs
// Parse and validate
$parsed = Uuid::fromString(\"f47ac10b-58cc-4372-a567-0e02b2c3d479\");
echo $parsed->getVersion(); // 4
// Check if a string is a valid UUID
try {
Uuid::fromString(\"not-a-uuid\");
} catch (\\Ramsey\\Uuid\\Exception\\InvalidUuidStringException $e) {
echo \"Invalid UUID\";
}
Without Dependencies: random_bytes()
<?php
function generateUuidV4(): string {
$bytes = random_bytes(16);
// Set version 4 (0100xxxx in byte 6)
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
// Set variant 1 (10xxxxxx in byte 8)
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
return vsprintf(\"%s%s-%s-%s-%s-%s%s%s\", str_split(bin2hex($bytes), 4));
}
echo generateUuidV4(); // \"550e8400-e29b-41d4-a716-446655440000\"
Database Column Types
| Database | Column Type | Storage |
|---|---|---|
| MySQL 8.0+ | BINARY(16) or CHAR(36) | 16 or 36 bytes |
| PostgreSQL | UUID (native type) | 16 bytes |
| MariaDB 10.7+ | UUID (native type) | 16 bytes |
| SQLite | TEXT or BLOB(16) | 36 or 16 bytes |
For MySQL, use BINARY(16) with UUID_TO_BIN() and BIN_TO_UUID() functions for optimal storage and indexing. CHAR(36) works but uses 2.25x more space and is slower to index.
Laravel Integration
<?php
// Laravel uses ramsey/uuid internally
use Illuminate\\Support\\Str;
$uuid = Str::uuid()->toString();
$orderedUuid = Str::orderedUuid()->toString(); // Time-ordered for DB performance
// In migrations
Schema::create(\"orders\", function (Blueprint $table) {
$table->uuid(\"id\")->primary();
$table->string(\"customer_name\");
$table->timestamps();
});
// In models
class Order extends Model {
use HasUuids; // Laravel 9.30+
public $incrementing = false;
protected $keyType = \"string\";
}
UUID v4 vs v7: Which to Use
- UUID v4 — fully random, good for security tokens and external-facing IDs
- UUID v7 — time-ordered prefix with random suffix, dramatically better for database primary keys because B-tree indexes stay sequential