How to generate unique random value for each user in laravel and add it to database

前端 未结 8 1909
刺人心
刺人心 2020-12-29 08:44

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

相关标签:
8条回答
  • 2020-12-29 09:23

    This is good:

    do {
       $refrence_id = mt_rand( 1000000000, 9999999999 );
    } while ( DB::table( 'transations' )->where( 'RefrenceID', $refrence_id )->exists() );
    
    0 讨论(0)
  • 2020-12-29 09:24

    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();
    }
    
    0 讨论(0)
提交回复
热议问题