For a PHP UUID v4 generator without Composer, start with random_bytes(16), set the version and variant bits, and format the bytes as hexadecimal groups. A maintained library is a better fit when you also need parsing, namespace UUIDs or UUID v7.
Key takeaways
- Use framework helpers or maintained packages for generation.
- Validate route and request UUIDs before database lookup.
- Prefer one storage format across the whole application.
For implementation context, continue with UUID v4, SQL, and UUID Regex. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.
Generate UUID v4 in plain PHP without a library
This function uses random_bytes(), available in PHP 7 and later. It keeps 122 random bits and sets the six fixed version and variant bits. Let a randomness failure raise an exception rather than falling back to a weaker generator.
<?php
function uuid_v4(): string
{
$bytes = random_bytes(16);
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
$hex = bin2hex($bytes);
return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-'
. substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-'
. substr($hex, 20, 12);
}
echo uuid_v4(), PHP_EOL;Use ramsey/uuid with Composer
Install the package with composer require ramsey/uuid. The example below uses its UUID v4 generator and converts the returned object to canonical text. Load your Composer autoloader before calling the library.
<?php
require __DIR__ . '/vendor/autoload.php';
$id = \Ramsey\Uuid\Uuid::uuid4()->toString();
echo $id, PHP_EOL;Generate a UUID in Laravel
Inside a bootstrapped Laravel application, Str::uuid() returns a UUID v4. Use the framework helper when you already depend on Laravel rather than maintaining a second implementation.
<?php
use Illuminate\Support\Str;
$id = (string) Str::uuid();Validate a UUID v4 in PHP
When an endpoint specifically requires UUID v4, check both the version digit and the standard variant. This example accepts canonical hyphenated text in either case. Validation confirms the shape, not ownership or whether the referenced record exists.
<?php
function is_uuid_v4(string $value): bool
{
return preg_match(
'/\A[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i',
$value
) === 1;
}UUIDs in Laravel models
If a model uses UUID primary keys, configure the key type and incrementing behavior deliberately. Model traits can choose a different UUID version from Str::uuid(); check the behavior of your installed framework version rather than assuming every helper creates v4. Decide whether your application or database owns generation.
Binary vs text storage
Text UUIDs are simple and portable. Binary UUID storage can save space, but it adds conversion rules and makes manual debugging harder. For many PHP apps, native database UUID support or canonical text is the better tradeoff.