Laravel UUID generation



PHP Snippet 1:

use Illuminate\Support\Str;

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

PHP Snippet 2:

// 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)
    );
}

PHP Snippet 3:


<?php

namespace App\Models\Traits;

use Ramsey\Uuid\Uuid as PackageUuid;

trait Uuid
{

    public function scopeUuid($query, $uuid)
    {
        return $query->where($this->getUuidName(), $uuid);
    }

    public function getUuidName()
    {
        return property_exists($this, 'uuidName') ? $this->uuidName : 'uuid';
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->{$model->getUuidName()} = PackageUuid::uuid4()->toString();
        });
    }
}

PHP Snippet 4:

use Illuminate\Support\Facades\DB;


public static function boot(){
    parent::boot();
    $creationCallback = function ($model) {
        if (empty($model->{$model->getKeyName()}))
            $model->{$model->getKeyName()} = DB::raw('uuid()');
    };
    static::creating($creationCallback);
}