Code guide

Generate UUIDs in PHP

Generate UUIDs in PHP, validate incoming UUID strings and choose storage formats for Laravel, Symfony and plain PHP apps.

PHP applications usually generate UUIDs through a framework helper or a trusted package. The main decision is not just how to create the value, but where to create it and how consistently the app stores it.

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.

Generating UUIDs in modern PHP apps

Laravel, Symfony and common PHP packages all provide UUID helpers. Use the helper your framework already supports so validation, casting and database integration stay boring.

<?php

use Illuminate\Support\Str;

$id = (string) Str::uuid();

Plain PHP validation pattern

If you only need to validate input shape, use a strict regex and keep authorization separate. The regex below accepts common UUID versions and the standard variant nibble.

<?php

function is_uuid(string $value): bool
{
    return preg_match(
        '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
        $value
    ) === 1;
}

UUIDs in Laravel models

If a model uses UUID primary keys, configure the key type and incrementing behavior deliberately. Also decide whether the application or the database creates the UUID. Mixing both can cause confusing tests and migrations.

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.

FAQ

Generate UUIDs in PHP questions

Can Laravel generate UUIDs?

Yes. Laravel includes string helpers for UUID generation, and many projects also use database UUID columns or model traits.

Should PHP generate UUIDs or should the database?

Either can work. Pick one owner for each table so imports, tests and migrations behave consistently.

Are PHP GUIDs different from UUIDs?

For the common string format, GUID and UUID values are usually the same shape.

Generate UUID in PHP - Examples for Apps and APIs