1

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 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.