如何在laravel中生成唯一ID?

shr*_*ooq 4 php uniqueidentifier laravel

我正在 Laravel 中处理我的毕业项目,并且想要生成小的唯一 ID“9 个字符最大”......我不需要 UUID,因为这将生成 36 个字符太长了。

nay*_*dev 15

您可以像这样使用 PHP 函数:

function unique_code($limit)
{
  return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
echo unique_code(9);
Run Code Online (Sandbox Code Playgroud)

输出看起来像:

s5s108dfc
Run Code Online (Sandbox Code Playgroud)

这里的规格:

  • base_convert – 在任意基数之间转换数字。
  • sha1 – 计算字符串的 sha1 哈希值。
  • uniqid – 生成唯一 ID。
  • mt_rand – 通过 Mersenne Twister 随机数生成器生成随机值。

或者在 Laravel 中你可以使用 laravel Str 库:只需使用这个:

use Illuminate\Support\Str;
$uniqid = Str::random(9);
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用此库生成随机字符串:

use Illuminate\Support\Str;

$id = Str::random(9);
Run Code Online (Sandbox Code Playgroud)