Ramsey/UUID for PHP: Complete Guide with Examples
1. What It Is and Why You Need It
The Ramsey/UUID library is the de facto standard for working with UUIDs (Universally Unique Identifiers) in the PHP ecosystem. A UUID is a 128-bit identifier that guarantees uniqueness without requiring a centralized coordinator. This library provides a full toolkit for generating, parsing, validating, and serializing UUIDs across all standard versions (v1, v3, v4, v5, v6, v7, v8), plus support for custom formats.
Why does this matter? In modern distributed systems, microservice architectures, and databases (especially NoSQL), UUIDs have become indispensable. They let you generate unique identifiers on the client or server without hitting the database — critical for offline modes, sharding, and replication. Ramsey/UUID eliminates collision risks, supports deterministic generation (v3/v5 via hashes), and includes timestamps (v1/v6/v7) for time-based sorting.
The library fully supports PSR-4, PSR-11 (containers), PSR-20 (Clock), and is actively maintained by the community. It powers major projects like Laravel, Symfony, Drupal, and CakePHP.
2. Installation
Install via Composer — PHP's standard package manager. Run this in your project root:
composer require ramsey/uuid
If you only need UUID v4 (random) support, install the lightweight version without extension dependencies:
composer require ramsey/uuid:^4.0
For UUID v1 (time-based) you'll need the ext-uuid extension (PECL), but the library can also fall back to pure PHP. Recommended PHP version is 8.0 or higher.
3. Quick Start — Minimal Working Example
The easiest way to begin is generating a UUID v4 (random). Create a file called test.php:
<?php
require_once 'vendor/autoload.php';
use Ramsey\Uuid\Uuid;
// Generate a UUID v4
$uuid = Uuid::uuid4();
echo $uuid->toString(); // Output: 550e8400-e29b-41d4-a716-446655440000
?>
Run it from the console: php test.php. You'll get a unique identifier. That's all you need for basic usage.
4. Key Methods / Functions / Classes
Below are 8 essential methods from the Ramsey/UUID library. Each method includes its signature, a brief description, and a working example.
4.1 Uuid::uuid4() — Generate Random UUID (v4)
Signature: public static function uuid4(): UuidInterface
Description: Generates a version 4 UUID using a cryptographically secure random number generator. The most popular choice for most use cases.
<?php
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4();
echo $uuid->toString(); // Example: 123e4567-e89b-12d3-a456-426614174000
?>
4.2 Uuid::uuid1() — Generate Time-Based UUID (v1)
Signature: public static function uuid1(?string $node = null, ?int $clockSeq = null): UuidInterface
Description: Generates a version 1 UUID that includes a timestamp (100-nanosecond intervals since 1582) and the node's MAC address. Useful when you need to sort records by creation time.
<?php
use Ramsey\Uuid\Uuid;
// Simple generation
$uuid1 = Uuid::uuid1();
echo $uuid1->toString(); // Example: c232ab00-9414-11ec-b909-0242ac120002
?>
4.3 Uuid::uuid3() — Generate Name-Based UUID (v3, MD5)
Signature: public static function uuid3(UuidInterface|string $ns, string $name): UuidInterface
Description: Generates a deterministic UUID v3 using MD5 hashing of a namespace and a name. Same inputs always produce the same UUID.
<?php
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'example.com');
echo $uuid3->toString(); // Example: 9073926b-929f-31c2-abc9-fad77ae3e8eb
?>
4.4 Uuid::uuid5() — Generate Name-Based UUID (v5, SHA-1)
Signature: public static function uuid5(UuidInterface|string $ns, string $name): UuidInterface
Description: Similar to v3 but uses SHA-1 hashing instead of MD5. Recommended over v3 for new projects due to better collision resistance.
<?php
use Ramsey\Uuid\Uuid;
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_URL, 'https://example.com/page');
echo $uuid5->toString(); // Example: 4e8c5a6b-7d8c-5f9a-bcde-f123456789ab
?>
4.5 Uuid::uuid6() — Generate Reordered Time-Based UUID (v6)
Signature: public static function uuid6(?UuidInterface $node = null, ?int $clockSeq = null): UuidInterface
Description: A newer version (RFC 9562) that reorders the timestamp fields for better database index performance compared to v1. Ideal for primary keys in MySQL or PostgreSQL.
<?php
use Ramsey\Uuid\Uuid;
$uuid6 = Uuid::uuid6();
echo $uuid6->toString(); // Example: 1ec94132-c232-6b00-b909-0242ac120002
?>
4.6 Uuid::uuid7() — Generate Unix Timestamp UUID (v7)
Signature: public static function uuid7(?int $timestamp = null): UuidInterface
Description: Generates a UUID v7 with a Unix timestamp in milliseconds (48 bits) followed by random data. Perfect for time-ordered, sortable identifiers in modern applications.
<?php
use Ramsey\Uuid\Uuid;
$uuid7 = Uuid::uuid7();
echo $uuid7->toString(); // Example: 018f3a6b-7c8d-7e9f-a012-3456789abcde
?>
4.7 Uuid::fromString() — Parse UUID from String
Signature: public static function fromString(string $uuid): UuidInterface
Description: Parses a UUID string (with or without hyphens, curly braces, or URN prefix) into a UuidInterface object for further manipulation.
<?php
use Ramsey\Uuid\Uuid;
$uuid = Uuid::fromString('550e8400-e29b-41d4-a716-446655440000');
echo $uuid->getVersion(); // Output: 4 (UUID v4)
?>
4.8 Uuid::isValid() — Validate UUID String
Signature: public static function isValid(string $uuid): bool
Description: Checks whether a given string is a valid UUID in any standard format. Returns true or false.
<?php
use Ramsey\Uuid\Uuid;
$valid = Uuid::isValid('550e8400-e29b-41d4-a716-446655440000'); // true
$invalid = Uuid::isValid('not-a-uuid'); // false
?>
5. Practical Examples
5.1 Using UUID as Primary Key in Laravel
In Laravel Eloquent models, you can use UUIDs instead of auto-increment IDs:
<?php
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
class User extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::uuid7()->toString();
});
}
}
?>
5.2 Generating Multiple UUIDs in a Loop
<?php
use Ramsey\Uuid\Uuid;
$uuids = [];
for ($i = 0; $i < 5; $i++) {
$uuids[] = Uuid::uuid4()->toString();
}
print_r($uuids);
?>
5.3 Extracting Timestamp from UUID v1
<?php
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid1();
$datetime = $uuid->getDateTime();
echo $datetime->format('Y-m-d H:i:s'); // Example: 2024-01-15 14:30:00
?>
6. Best Practices and Tips
- Use UUID v7 for primary keys — it's time-ordered, index-friendly, and avoids fragmentation in B-tree indexes.
- Store as binary(16) in MySQL or PostgreSQL for better performance instead of varchar(36).
- Cache the UuidFactory if generating many UUIDs in a loop to avoid repeated initialization overhead.
- Use deterministic UUIDs (v3/v5) when you need the same ID for the same data across systems.
- Always validate user-supplied UUIDs with
Uuid::isValid()before processing.
7. Conclusion
Ramsey/UUID is the most robust and feature-complete UUID library for PHP. Whether you're building a microservice, a distributed system, or just need unique IDs without a database round-trip, this library has you covered. Start with uuid4() for simplicity, then explore v7 for time-ordered IDs and v3/v5 for deterministic generation.
For the official documentation, visit uuid.ramsey.dev. Happy coding!