Laravel UUID generation

In Laravel 5.6+

use Illuminate\Support\Str;

$uuid = Str::uuid()->toString();

Turns out I had to use $uuid->string to get the actual ID, the whole object shows empty if you try to return it in a json response.


It's possible that $uuid is empty because your system doesn't provide the right kind of entropy. You might try these library implementations for either a v4 or v5 UUID:

// https://tools.ietf.org/html/rfc4122#section-4.4
function v4() {
    $data = openssl_random_pseudo_bytes(16, $secure);
    if (false === $data) { return false; }
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

// https://tools.ietf.org/html/rfc4122#section-4.3
function v5($name) {
    $hash = sha1($name, false);
    return sprintf(
        '%s-%s-5%s-%s-%s',
        substr($hash,  0,  8),
        substr($hash,  8,  4),
        substr($hash, 17,  3),
        substr($hash, 24,  4),
        substr($hash, 32, 12)
    );
}

After laravel 5.6 a new helper was added to generate Universal Unique Identifiers (UUID)

use Illuminate\Support\Str;

return (string) Str::uuid();

return (string) Str::orderedUuid();

The methods return a Ramsey\Uuid\Uuid object

The orderedUuid() method will generate a timestamp first UUID for easier and more efficient database indexing.

Tags:

Php

Uuid

Laravel