lundi 24 juillet 2023

Generate a random account unique number, using php, and laravel [closed]

Hi guys am not asking the question but i just want to share my idea on how i have implement it

Here is the my method on a controller

public function generateAndInsertTheAccountNumbers(Request $request)
    {
        $data = $request->validate(['numberOfAccounts' => "required|numeric"]);
        $numberOfBankAccountToGenerate = $data['numberOfAccounts'];
        $errorTimes = 0;
        $min = 1000000
        $max = 9999999
        for ($i = 0; $i < $numberOfBankAccountToGenerate; $i++) {
            try {
                AccountNumber::create(['accountNumber' => rand($min, $max)]);
            } catch (\Throwable $th) {
                $i--;
                $errorTimes ++;
            }
        }
        return response(['message' => "Successfully generate total of ".$numberOfBankAccountToGenerate." account numbers contain errors times ".$errorTimes]);
    }

So basically what am doing here is am generating the account number then store them on my db as you can see the number are not generated on demand as when the user is registering we just pick the first number that we could find in the account number table then use it then delete it from the account table, so in my model of accountnumber the accountNumber column is unique so if there was a repeation of the number we will try to generate a new account number that's it.

As of now the solution is fine, because we combine the number with other numbers that is unique to the user so if we combine with the account number that we generate we get a unique account number, i hope it helps someone out there.

NOTE: This is just a simple solution to my problem and it is not pure randomness if you want to have a pure random number consider go and see the api provided by random org




Aucun commentaire:

Enregistrer un commentaire