简体   繁体   English

如何在 laravel 中生成唯一 ID?

[英]How I can generate the unique ID in laravel?

I'm working with my graduation project in Laravel, and want to generate small unique ID "9 char max"... I don't need UUID because this will generate 36 char which is too long.我正在 Laravel 中处理我的毕业项目,并且想要生成小的唯一 ID“最大 9 个字符”...我不需要 UUID,因为这会生成 36 个字符,这太长了。

You can use PHP function like this:您可以像这样使用 PHP function :

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

Output looks like: Output 看起来像:

s5s108dfc

Here the specifications:这里的规格:

  • base_convert – Convert a number between arbitrary bases. base_convert – 在任意基数之间转换一个数字。
  • sha1 – Calculate the sha1 hash of a string. sha1 – 计算字符串的 sha1 hash。
  • uniqid – Generate a unique ID. uniqid – 生成唯一 ID。
  • mt_rand – Generate a random value via the Mersenne Twister Random Number Generator. mt_rand – 通过 Mersenne Twister 随机数生成器生成一个随机值。

Or in Laravel you can use laravel Str library: just use this:或者在 Laravel 中,您可以使用 laravel Str 库:只需使用这个:

use Illuminate\Support\Str;
$uniqid = Str::random(9);

You can generate a random string with this library:您可以使用此库生成随机字符串:

use Illuminate\Support\Str;使用 Illuminate\Support\Str;

$id = Str::random(9); $id = Str::random(9);

You can use this,你可以用这个,

$unique_id= echo floor(time()-999999999);

this is generating a 9 digit unique value based on time.这是根据时间生成一个 9 位数的唯一值。

Generate custom Unique ID or Code (With Prefix or Suffix Or Both Or Only Unique Id) Or reset your ID after the change of Prefix or Suffix Or Both in laravel framework在 laravel 框架中生成自定义唯一 ID 或代码(带前缀或后缀或两者或仅唯一 ID)或在更改前缀或后缀或两者后重置您的 ID

Visit https://github.com/SirajCse/laravel-unique-id-generator访问https://github.com/SirajCse/laravel-unique-id-generator

Example: Inv-000001/12/21示例:Inv-000001/12/21

UniqueIdGenerator::generate(['table' => 'invoices','field'=>'invoice_id','length' => 16,'prefix' => 'Inv-', 'suffix' => date('/m/y')]);

'table' => 'invoices' [sting table name]
'field'=>'invoice_id' [Default 'id'] [Optional][any string field name]
'length' => 12 [Integer value Id length]
'prefix'=>'Inv-' [Default ''] [Optional] [any string]
'suffix'=>date('/m/y') [Default ''] [Optional][any string]
'reset_on_change'=>false[ Default false] [Optional] [Options are 1.prefix , 2.suffix 3.both 4.false]
uniqueId=000001

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM