ChatGPT解决这个技术问题 Extra ChatGPT

Laravel UUID generation

I am trying to generate a UUID (not as primary key, just generate one) with the laravel-uuid package. The docs are pretty straightforward, so according to the readme file a UUID should be generated just by calling $uuid = Uuid::generate();, but it returns an empty object. (I also tried $uuid = Uuid::generate(1);)

I followed the installation instructions as provided there (nothing out of the ordinary), the app doesn't throw any errors, so I guess everything is right.

Alternative packages for this are also welcome.

try echo Uuid::generate() or $uuid = Uuid::generate(); echo $uuid->string
I second what @BenSwinburne said: looking at the source seems like you should be able to do echo Uuid::generate()->time to get back the v1 UUID. Or ->string to get the string version.
Got it to work... turns out the object is returned empty if I try to return it with a response, and when I used $uuid->string it worked. Thanks!

T
Toby Allen

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.


Valid for laravel 7 as well. Thanks
Works for Laravel 8 too.
A
Andrew Koper

In Laravel 5.6+

use Illuminate\Support\Str;

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

You don't need toString()
S
Skatch

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.


You can add the uuid field as part of the casts section within the model For my case, the id was the uuid field and to return the actual uuid as part of the response, I had to cast it as below. protected $casts = ['id' => 'string'];
b
bishop

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

thanks mate, I'll try this as a last resort, I wanted to use something built for laravel
N
Nurzaly Abd Rahman

add column in table name 'Uuid', type 'char' length 36 create folder name 'Traits' inside Models folder Create file name Uuid.php inside Traits folder

Uuid.php


<?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();
        });
    }
}

add 'use Uuid' inside your model


E
Emad Adly

Try to use this package will automatically generate and assign UUID field in your model, also can show and update by UUIDs key.

https://github.com/EmadAdly/laravel-uuid


S
Soubhagya Kumar Barik

for laravel < 5.6

use DB::raw('uuid()');

please have a look at below example

inside model

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

Pros

--You don't have to use any third-party plugin to get UUID in case you are using laravel < 5.6

Cons

after saving the data using ORM you need to query again to get the last inserted id otherwise you will get uuid().