Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in Laravel

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

like image 808
kacyblack Avatar asked Jul 22 '14 09:07

kacyblack


People also ask

What is Mt_rand function in PHP?

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.

How to generate random number with PHP?

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.

How do you generate random unique strings in laravel?

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.

How to generate random 4 digit number in Laravel?

You can use the random_int() function to generate 2,4,6,10, digit unique random number in PHP Laravel.


1 Answers

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).

like image 141
Luís Cruz Avatar answered Oct 05 '22 20:10

Luís Cruz