0

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 auto increment One solution is to grab all the auto increment numbers in an array and generate a auto increment number using laravel takes the form (0000000001 to 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?

4 Answers4

1

Select Maximum number stored in your DB and add 1 in it like:

SELECT (MAX(Column_Name)+1) AS Max_val FROM Table_Name;
Muhammad Bilal
  • 497
  • 1
  • 5
  • 12
  • This is the only realistic solution that will also auto increment. It's not random, but does OP actually really need it to be? – Andrei Oct 09 '19 at 06:19
1

I suggest simple timestamp-based solution using the Carbon class to produce a unique number using timestamp. It's fairly simple to have a basic unique and random stamp generation using timestamp. You can use as given below,

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like this 1552296328

You can use it as a unique identifier. If you want the next numbers, just +1. But keep in mind, you have to manage another number batch in a timely manner. (i.e if you have generated 500 numbers for now by increment, You should not generate another number for the next 500 seconds. Otherwise, it will repeat the number). If you want to know more, you can read here.

The solution with rand() function may not work here because it can re-produce the existing number in the database and you will be errored for Unique Constraint Violation(i.e. If you have column unique in DB).

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
0

No matter what approach you use, it would never be truly random. It will be PRNG. For your case, I think auto increment with zero fill should be enough.

But if you are set on using random number then using rand() function of PHP should be enough. 10 digit means 10000000000 unique number.Unless your project has millions of events it should realistically be no problem. So, approach 1 should be no problem. Also, you can check after generating any random number that whether that number is already present(There is 0.000001% or something like that chance.). If it is present then try to generate a random number again.

But if your project gets very successful (I.E. millions of events) then problems similar to Y2K might creep up.

Nabil Farhan
  • 1,444
  • 3
  • 25
  • 41
0

MySQL UUID would give you truly unique is: Store UUID v4 in MySQL

You don’t need to worry about auto incrementing.

Shaunak Sontakke
  • 980
  • 1
  • 7
  • 17