I am developing a event organization website. Here when the user registers for an event he will be given a unique random number(10 digit), which we use to generate a barcode and mail it to him. Now,

  1. I want to make the number unique for each registered event.
  2. And also random

One solution is to grab all the random numbers in an array and generate a random number using Php rand(1000000000, 9999999999) and loop through and check all the values. Grab the first value that doesn't equal to any of the values in the array and add it to the database.

But I am thinking that there might be a better solution to this. Any suggestion?

推荐答案

Your logic isn't technically faulty. However, if your application attracts lots of users, fetching all of the random numbers may well become unnecessarily expensive, in terms of resources and computation time.

I would suggest another approach, where you generate a random number and then check it against the database.

function generateBarcodeNumber() {
    $number = mt_rand(1000000000, 9999999999); // better than rand()

    // call the same function if the barcode exists already
    if (barcodeNumberExists($number)) {
        return generateBarcodeNumber();
    }

    // otherwise, it's valid and can be used
    return $number;
}

function barcodeNumberExists($number) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return User::whereBarcodeNumber($number)->exists();
}

Laravel相关问答推荐

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

为什么使用 created_at 表在迁移错误中创建表?

如何在 Laravel 9 中获取带分页的订单列表?

分页计数(*)查询问题

如何保存/重定向 Laravel Artisan 命令的输出?

try 发布 AJAX 请求时 POST 405(方法不允许)-Laravel 4

如何在 Laravel 中使用内存数据库的完整测试套件之前迁移和 seeder ?

自定义 Laravel 关系?

如何在laravel中将数组转换为字符串?

如何处理 Laravel 的 SMTP 驱动程序中的自签名 TLS 证书?

限制 Blade foreach 循环中的结果

如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

SQLSTATE [HY000]:一般错误:1005 无法创建表 - Laravel 4

Laravel 5:完整性约束违规:1452 无法添加或更新子行:外键约束失败

在 Laravel 的 Homestead 中运行 PHPUnit

如何在 laravel 中解码 Json 对象并在 laravel 中应用 foreach 循环

Laravel assets资源与混合

日期时间格式无效:1366 字符串值不正确

Distinct values with pluck

找不到 HOME 环境 -- 扩展 `~'