Skip to main content
PHP

How to Generate UUID in PHP

Using ramsey/uuid package

PHP's standard library doesn't ship a UUID generator, but the ramsey/uuid Composer package fills that gap and has become the de facto standard for the job. Install it once, then call Uuid::uuid4() for a random, RFC 9562-compliant UUID anywhere in your codebase, whether that's an Eloquent model, a Symfony entity, or a plain PDO insert. Below you'll find copy-paste ready code for generating a PHP UUID, converting a string back into a UUID object, and the alternate uuid1()/uuid5() generation methods the same package provides. The scala uuid reference explains how to use UUID.randomUUID() in idiomatic Scala with type safety.

Generate UUID in PHP

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

How to Generate a UUID in PHP

The reliable way to generate a UUID in PHP is the ramsey/uuid package's Uuid::uuid4() method, which produces a random, cryptographically secure 128-bit identifier — PHP has no native function for this. Install it once with Composer and it works the same way in plain scripts, Laravel, Symfony, or any other framework. For Node.js UUID generation without npm, the node.js uuid guide uses the built-in crypto module directly.

terminal
composer require ramsey/uuid
generate-uuid.php
<?php
require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;

$myUuid = Uuid::uuid4();
echo $myUuid->toString();
// Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in PHP

When a UUID arrives as a string — from a request body, a form field, or a database row — parse it back into a proper UuidInterface object with Uuid::fromString(). For zero-dependency UUID generation, the python uuid module is included in the Python standard library.

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

use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\InvalidUuidStringException;

$uuidString = '550e8400-e29b-41d4-a716-446655440000';

try {
    $uuid = Uuid::fromString($uuidString);
    echo $uuid->toString();
} catch (InvalidUuidStringException $e) {
    echo 'Invalid UUID format';
}

Explanation

Other Options for Generating UUIDs in PHP

uuid4() covers most use cases, but the same ramsey/uuid package also ships uuid1() and uuid5() for when you need a timestamp-based or deterministic identifier instead of a random one — no extra install required. PHP's PECL uuid extension offers a native uuid_create() function too, but it isn't enabled by default on most hosts, so ramsey/uuid stays the more portable choice.

other-versions.php
<?php
use Ramsey\Uuid\Uuid;

// Version 1 - timestamp + node ID, sortable by creation time
$uuid1 = Uuid::uuid1();

// Version 5 - deterministic, same namespace + name always produce the same UUID
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com');

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!