How to Generate UUID in PHP
- PHP has no built-in UUID function — use the ramsey/uuid package (the standard) or com_create_guid() on Windows.
- composer require ramsey/uuid — then Uuid::uuid4()->toString() generates a UUID v4.
- Laravel has Str::uuid() built-in — no additional package needed.
- Symfony provides UuidFactory via symfony/uid component.
- Store UUIDs as CHAR(36) or BINARY(16) in MySQL; use native UUID type in PostgreSQL.
Table of Contents
PHP does not have a built-in UUID function in its standard library, but the ramsey/uuid package is the widely accepted standard — it is a dependency of Laravel, Symfony, and most major PHP frameworks. This guide covers the options from simplest to most feature-complete.
ramsey/uuid — The Standard PHP UUID Library
composer require ramsey/uuid
<?php
use RamseyUuidUuid;
// Generate UUID v4:
$id = Uuid::uuid4();
echo $id; // 550e8400-e29b-41d4-a716-446655440000
echo $id->toString(); // same — explicit string conversion
// As a plain string variable:
$uuid = Uuid::uuid4()->toString();
// UUID v5 (deterministic):
$namespace = Uuid::fromString('6ba7b811-9dad-11d1-80b4-00c04fd430c8');
$id = Uuid::uuid5($namespace, 'https://example.com/user/123');
echo $id; // Always the same for the same inputs
UUID in Laravel — Built-In Str::uuid()
<?php
use IlluminateSupportStr;
// Generate UUID v4 — no package needed (uses ramsey/uuid internally):
$id = Str::uuid();
echo $id; // 550e8400-e29b-41d4-a716-446655440000
$idStr = (string) Str::uuid(); // explicit string cast
// Ordered UUID (better for database index performance):
$orderedId = Str::orderedUuid();
// Time-prefixed UUID — similar to UUID v7
// In Eloquent models — auto UUID primary key:
use IlluminateDatabaseEloquentConcernsHasUuids;
class Order extends Model {
use HasUuids;
// $order->id is automatically a UUID v4
}
// In migrations:
Schema::create('orders', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('status');
$table->timestamps();
});
Sell Custom Apparel — We Handle Printing & Free Shipping
UUID in Symfony — symfony/uid Component
composer require symfony/uid
<?php
use SymfonyComponentUidUuid;
use SymfonyComponentUidUuidV4;
use SymfonyComponentUidUuidV7;
// Generate UUID v4:
$id = Uuid::v4();
echo $id; // 550e8400-e29b-41d4-a716-446655440000
echo $id->toRfc4122(); // same — explicit RFC format
// UUID v7 (time-ordered):
$id = Uuid::v7();
// Validate:
Uuid::isValid('550e8400-e29b-41d4-a716-446655440000'); // true
Uuid::isValid('not-a-uuid'); // false
// In Doctrine entities:
use SymfonyBridgeDoctrineTypesUuidType;
use SymfonyComponentUidUuid;
class Order {
#[ORMId]
#[ORMColumn(type: UuidType::NAME, unique: true)]
#[ORMGeneratedValue(strategy: 'CUSTOM')]
#[ORMCustomIdGenerator(class: 'doctrine.uuid_generator')]
private Uuid $id;
}
Pure PHP UUID Without Composer
If you cannot use Composer, here is a standalone UUID v4 implementation:
<?php
function generateUUIDv4(): string {
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // version 4
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant bits
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
echo generateUUIDv4(); // 550e8400-e29b-41d4-a716-446655440000
random_bytes() uses a cryptographically secure source (available since PHP 7.0). This produces a valid RFC 4122 UUID v4 with no dependencies.
On Windows with PHP < 7 and COM extension available:
$guid = com_create_guid();
$uuid = strtolower(trim($guid, '{}')); // strip braces, lowercase
UUID Validation and Database Storage in PHP
<?php
// Validate UUID format with regex:
function isValidUUID(string $uuid): bool {
return (bool) preg_match(
'/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
$uuid
);
}
// PDO — store as CHAR(36) in MySQL:
$stmt = $pdo->prepare('INSERT INTO orders (id, status) VALUES (:id, :status)');
$stmt->execute([
':id' => Uuid::uuid4()->toString(),
':status' => 'pending',
]);
// Fetch and verify:
$row = $pdo->query('SELECT id FROM orders LIMIT 1')->fetch();
var_dump(isValidUUID($row['id'])); // bool(true)
Generate a UUID Without Installing ramsey/uuid
Get a ready-to-use UUID v4 from the Cheetah UUID Generator — paste directly into your PHP database seed, migration file, or unit test.
Open Free UUID GeneratorFrequently Asked Questions
Does PHP have a built-in UUID function?
No. PHP has no native UUID function in its standard library. The ramsey/uuid package is the standard solution. Laravel and Symfony include UUID support via ramsey/uuid and symfony/uid respectively.
What is the difference between Str::uuid() and Str::orderedUuid() in Laravel?
Str::uuid() generates a random UUID v4. Str::orderedUuid() generates a time-ordered UUID (similar to UUID v7) that inserts sequentially into database indexes, reducing fragmentation in high-write scenarios.
How do I generate a UUID in PHP without installing a package?
Use random_bytes(16) and format it as a UUID with the version and variant bits set. The pure PHP function in this guide does this in about 5 lines. Available since PHP 7.0.
Should I store UUIDs as CHAR(36) or BINARY(16) in MySQL with PHP?
BINARY(16) is more efficient at scale (half the storage, faster indexes), but requires UUID_TO_BIN() / BIN_TO_UUID() in queries. CHAR(36) is simpler and readable — acceptable for most PHP applications that are not at extreme scale.
Does ramsey/uuid support UUID v7?
Yes, since ramsey/uuid v4.7 (2023). Use Uuid::uuid7() to generate a time-ordered UUID v7. Requires PHP 8.1+.

