我正在使用 Laravel 开发毕业项目,需要生成一个最长只有 9 个字符的小型唯一标识符。我不需要使用 UUID,因为这会生成长度为 36 个字符的标识符,太长了。
我正在使用 Laravel 开发毕业项目,需要生成一个最长只有 9 个字符的小型唯一标识符。我不需要使用 UUID,因为这会生成长度为 36 个字符的标识符,太长了。
function unique_code($limit)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
echo unique_code(9);
s5s108dfc
或者在 Laravel 中,您可以使用 Laravel Str 库: 只需使用以下代码:
use Illuminate\Support\Str;
$uniqid = Str::random(9);
Str::random
方法是否有确保唯一性的功能? - Hashim Aziz$unique_id= echo floor(time()-999999999);
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
在 Laravel 中创建自定义辅助方法
它将根据条件生成序列随机数。
function generateSequenceNumber($tablename, array $conditions = [], string $prefix, int $length = 5): string
{
$model = \DB::table($tablename);
if (is_array($conditions) && count($conditions) > 0) {
$model = $model->where($conditions);
}
return $prefix . str_pad(
($model->count()) + 1,
$length,
'0',
STR_PAD_LEFT
);
}
generateSequenceNumber('tablename',[],'prefix-',5); //prefix-00001
generateSequenceNumber('users',['role' => 'admin'],'admin-',5); //admin-00005
generateSequenceNumber('users',['is_active' => 1,'role' => 'client'],'client-',8);
//client-00000008