Try it here
Generate a UUID to paste into your PHP code, in any version and format.
Your UUIDs
Copy one, copy them all, or download the list. The format options above apply to everything shown here.
The standard library choice: ramsey/uuid
composer require ramsey/uuid
use Ramsey\Uuid\Uuid;
$id = Uuid::uuid4()->toString(); // random v4
$id7 = Uuid::uuid7()->toString(); // time ordered v7, use for database keys
$id5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com')->toString();
$id1 = Uuid::uuid1()->toString(); // time based v1
Uuid::isValid($input); // true or false
$u = Uuid::fromString($input); // throws InvalidUuidStringException
$u->getVersion(); // 4
$u->getBytes(); // 16 bytes for BINARY(16) columns
ramsey/uuid is the package almost every PHP project uses, and Laravel depends on it. Prefer v7 for primary keys, the reasons are on the v7 page.
Laravel
use Illuminate\Support\Str;
Str::uuid(); // v4, returns a UuidInterface, cast to string when storing
Str::uuid7(); // v7, Laravel 11.x and newer
Str::orderedUuid(); // older time ordered variant, kept for compatibility
// Eloquent, Laravel 9+
use Illuminate\Database\Eloquent\Concerns\HasUuids;
class Order extends Model
{
use HasUuids; // v7 keys on Laravel 12, orderedUuid on 9 to 11
}
// migration
$table->uuid('id')->primary();
Symfony
composer require symfony/uid
use Symfony\Component\Uid\Uuid;
Uuid::v4();
Uuid::v7();
Uuid::isValid($input);
Uuid::fromString($input)->toRfc4122();
Without a dependency
function uuid4(): string
{
$b = random_bytes(16);
$b[6] = chr((ord($b[6]) & 0x0f) | 0x40); // version 4
$b[8] = chr((ord($b[8]) & 0x3f) | 0x80); // variant RFC
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}
random_bytes is cryptographically secure and available since PHP 7.
Mistakes to avoid
- uniqid() is not a UUID. It is a hex timestamp with a few extra digits, predictable and not unique across machines.
- mt_rand and rand are not secure. Use random_bytes or the package.
- Storing as VARCHAR(36) when BINARY(16) would do. Use getBytes() and fromBytes() at the boundary, or Laravel's uuid column type on PostgreSQL.
Frequently asked questions
How do I generate a UUID in PHP without Composer?
Read 16 bytes from random_bytes, set the version and variant bits, and format as hex. The snippet above does it in five lines and produces a valid v4.
Does Laravel use UUID v4 or v7?
Str::uuid() is v4. Str::uuid7() gives v7 on Laravel 11 and newer. The HasUuids trait uses v7 from Laravel 12, and orderedUuid, a custom time ordered layout, on Laravel 9 to 11.
How should I store UUIDs in MySQL from PHP?
BINARY(16) with getBytes(). It halves the storage and speeds up index lookups compared with CHAR(36). Convert back with Uuid::fromBytes when reading.