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
The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max]. Syntax: rand(); The rand() function is used to generate a random integer.
If you need to generate unique random string then you can use str_random() helper of Laravel. It is very simple and you can use easily. you can easily generate random string in laravel 6, laravel 7, laravel 8 and laravel 9 version using str helper.
You can use the random_int() function to generate 2,4,6,10, digit unique random number in PHP Laravel.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With