PHP

How to Generate UUID in PHP

Using ramsey/uuid package

Generate UUIDs in PHP using the industry-standard ramsey/uuid package. Full support for all UUID versions (v1, v4, v5, v6, v7) with seamless Laravel, Symfony, and framework integration.

Generate UUID in PHP

Uuid::uuid4()
550e8400-e29b-41d4-a716-446655440000

Install ramsey/uuid via Composer

Composer Installation Required

ramsey/uuid is the most popular PHP UUID library with 350M+ downloads

composer require ramsey/uuid
350M+
Downloads
PHP 7.2+
Minimum Version
7 Versions
UUID Support

Generate All UUID Versions in PHP

uuid-generation.php
<?php
require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;

// UUID v4 - Random (most common)
$uuid4 = Uuid::uuid4();
echo $uuid4->toString();  // 550e8400-e29b-41d4-a716-446655440000

// UUID v1 - Timestamp + MAC address
$uuid1 = Uuid::uuid1();

// UUID v7 - Unix timestamp (sortable, recommended)
$uuid7 = Uuid::uuid7();

// UUID v6 - Reordered timestamp
$uuid6 = Uuid::uuid6();

// UUID v5 - SHA-1 hash (deterministic)
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com');

// UUID v3 - MD5 hash
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'example.com');

// Get as different formats
echo $uuid4->toString();       // With hyphens
echo $uuid4->getHex()->toString();  // Hex without hyphens

Framework Integration: Laravel vs Symfony

Laravel Model with UUID Primary Key

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;

class User extends Model
{
    use HasUuids;  // Auto UUID generation (Laravel 9+)
    
    protected $fillable = ['name', 'email'];
    
    // Alternative: manual UUID generation
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($model) {
            if (! $model->getKey()) {
                $model->{$model->getKeyName()} = (string) Str::uuid();
            }
        });
    }
}

// Migration
Schema::create('users', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

Parse, Validate & Compare UUIDs

Parse UUID from String

$uuid = Uuid::fromString('550e8400-e29b-41d4-a716-446655440000');
echo $uuid->toString();

Validate UUID Format

if (Uuid::isValid('550e8400-e29b-41d4-a716-446655440000')) {
    echo "Valid UUID";
}

Compare UUIDs

$uuid1 = Uuid::uuid4();
$uuid2 = Uuid::uuid4();

echo $uuid1->equals($uuid2) ? 'Equal' : 'Different';
echo $uuid1->compareTo($uuid2);  // -1, 0, or 1

PHP UUID Without External Libraries

For quick prototyping without Composer (not recommended for production):

simple-uuid.php
<?php
function generateUuidV4(): string {
    $data = random_bytes(16);
    
    // Set version to 4
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    
    // Set variant to RFC4122
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

echo generateUuidV4();  
// Output: 550e8400-e29b-41d4-a716-446655440000

Warning: This basic implementation only supports UUID v4 and lacks validation. Use ramsey/uuid for production applications.

Database Integration with PDO

pdo-uuid.php
<?php
use Ramsey\Uuid\Uuid;

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');

// Insert with UUID
$uuid = Uuid::uuid4();
$stmt = $pdo->prepare('INSERT INTO users (id, name, email) VALUES (?, ?, ?)');
$stmt->execute([
    $uuid->toString(),
    'Alice Smith',
    'alice@example.com'
]);

echo "Created user with ID: {$uuid->toString()}";

// Query by UUID
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute(['550e8400-e29b-41d4-a716-446655440000']);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Binary UUID storage (saves space)
$stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (UNHEX(REPLACE(?, "-", "")), ?)');
$stmt->execute([$uuid->toString(), 'Bob']);

UUID Comparison Matrix

Method Installation Versions Recommended
ramsey/uuid Composer v1, v3, v4, v5, v6, v7 ✓ Yes
symfony/uuid Composer v1, v4, v6, v7 Symfony
Native PHP None v4 only No

API Response with UUID Generation

api.php
<?php
use Ramsey\Uuid\Uuid;

header('Content-Type: application/json');

// POST /api/users
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $user = [
        'id' => Uuid::uuid4()->toString(),
        'name' => $input['name'],
        'email' => $input['email'],
        'created_at' => date('c')
    ];
    
    // Save to database...
    
    http_response_code(201);
    echo json_encode([
        'success' => true,
        'data' => $user
    ]);
}

// GET /api/users/{uuid}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $uuid = $_GET['id'] ?? '';
    
    if (!Uuid::isValid($uuid)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid UUID format']);
        exit;
    }
    
    // Fetch from database...
    echo json_encode(['success' => true, 'data' => $user]);
}

Related Programming Language UUID Guides

Copied!