Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 942
Nasif Md. Tanjim Avatar asked Feb 15 '15 08:02

Nasif Md. Tanjim


People also ask

How to create random number in Laravel?

You can use the rand() function to generate a random number. You can also create some characters and prefix the rand() with it.

How do I generate a random 10 digit number in Laravel?

You can use the random_int() function to generate 2,4,6,10, digit unique random number in PHP Laravel.


1 Answers

You can use php's uniqid() function to generate a unique ID based on the microtime (current time in microseconds)

Example:

<?php echo uniqid(); ?> 

Output:

56c3096338cdb 
like image 178
Abhijeet Ashok Muneshwar Avatar answered Sep 20 '22 05:09

Abhijeet Ashok Muneshwar