php Laravel UUID 生成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37948764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel UUID generation
提问by Skatch
I am trying to generate a UUID (not as primary key, just generate one) with the laravel-uuidpackage. 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);
)
我正在尝试使用laravel-uuid包生成一个 UUID(不是作为主键,只是生成一个)。文档非常简单,因此根据自述文件,只需调用 就应该生成 UUID $uuid = Uuid::generate();
,但它返回一个空对象。(我也试过$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.
也欢迎为此提供替代软件包。
采纳答案by 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.
原来我必须使用$uuid->string
来获取实际 ID,如果您尝试在 json 响应中返回它,则整个对象显示为空。
回答by Hemerson Varela
In laravel 5.6a new helpers were added to generate Universal Unique Identifiers (UUID)
在laravel 5.6中添加了一个新的助手来生成通用唯一标识符(UUID)
use Illuminate\Support\Str;
return (string) Str::uuid();
return (string) Str::orderedUuid();
The methods return a Ramsey\Uuid\Uuid
object
方法返回一个Ramsey\Uuid\Uuid
对象
The orderedUuid()
method will generate a timestamp first UUID for easier and more efficient database indexing.
该orderedUuid()
方法将首先生成时间戳 UUID,以便更轻松、更高效地进行数据库索引。
回答by Andrew Koper
In Laravel 5.6+
在 Laravel 5.6+
use Illuminate\Support\Str;
$uuid = Str::uuid()->toString();
回答by 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:
它可能$uuid
是空的,因为您的系统没有提供正确类型的熵。您可以为 v4 或 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)
);
}
回答by 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.
尝试使用这个包会在你的模型中自动生成和分配 UUID 字段,也可以通过 UUIDs 键显示和更新。