I need generate a unique code with only numbers. How can I generate unique code with str_random() with only numbers in Laravel?
1 Answer
There's a built in php function. This will generate a random number that is 6 characters long.
mt_rand(100000, 999999);
To ensure it's unique you need to query the database. If it's already in use, try again. Make sure to clear up codes that have been used.
Edit: Also, make sure the column in the table is marked as unique. Having accidentally not-unique identifiers can be a real headache.