Please am working on a Project on Laravel and I wanted to Generate a Random Number in this format: one character in any position order and the rest integers. Example: C87465398745635, 87474M745436475, 98487464655378J8 etc. and this is my Controller:
function generatePin( $number ) {
$pins = array();
for ($j=0; $j < $number; $j++) {
$string = str_random(15);
$pin = Pin::where('pin', '=', $string)->first();
if($pin){
$j--;
}else{
$pins[$j] = $string;
}
}
return $pins;
}
But it seems to be Generating something else like this: ZsbpEKw9lRHqGbv, i7LjvSiHgeGrNN8, pyJEcjhjd3zu9Su I have tried all I could but no success, Please any helping solution will be appreciated, Thanks
If you want to generate the random string like you said, replace:
$string = str_random(15);
with
// Available alpha caracters
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// generate a pin based on 2 * 7 digits + a random character
$pin = mt_rand(1000000, 9999999)
. mt_rand(1000000, 9999999)
. $characters[rand(0, strlen($characters) - 1)];
// shuffle the result
$string = str_shuffle($pin);
Edit:
Before, the code wasn't generating a random alpha character all the time. Thats because Laravel's str_random
generates a random alpha-numeric string, and sometimes that function returned a numeric value (see docs).