Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kikismedia's avatar

how can I generate 10 digit unique number that will be sent to user after registration on laravel

I would like to generate a 10 unique number for a user immediately they Register on the website sent via email and probably they will use the generated number to login to the website , teach me how to achieve this or help with directives I'm new to laravel and php

0 likes
9 replies
Kikismedia's avatar

I would like users to have it as an account number

martinbean's avatar

Just use an auto-incrementing number. Otherwise you’re constantly going to have to check a “random” number doesn’t already exist each time you generate one, as no random number generator is truly random.

sr57's avatar

In 2 times +

  1. $rn=rand(0,9).rand(0,9) ... (10 times or better with a loop)

1.1) better with @martinbean solution (Laravel solution versus plain php with rand)

  1. Check if this number does not exist for a user

  2. redo 1 & 2 if already exists (very low probability)

Magalliu's avatar
Magalliu
Best Answer
Level 2

Here, this is how I generate random 5 digit unique number for each user:

//Generating a random unique candidate_id for each applicant & adding 0 in upfront if id less than 5 digits
$candidatesData = Candidate::get(['candidate_id'])->toArray();
do {

$applicant_id = str_pad(rand(1, 5000), 5, "0", STR_PAD_LEFT);

} while (in_array($applicant_id, $candidatesData));

$candidate = Candidate::create($request->all());
$candidate->candidate_id = $applicant_id;
$candidate->save();

Please consider refactoring the code as per your needs.

2 likes

Please or to participate in this conversation.