Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel faker random number 10 digits


Laravel faker random number 10 digits


To generate a random 10-digit number using Laravel's Faker library, you can utilize the `randomNumber` method with the appropriate parameters. Here's how you can do it:

Generating a 10-Digit Number

You can use the following code snippet in your Laravel application:

php
$faker = \Faker\Factory::create();
$tenDigitNumber = $faker->randomNumber(10, true); // true ensures the number is not padded with zeros

Explanation

- `randomNumber($nbDigits, $strict)`: This method generates a random number with the specified number of digits. The first parameter, `$nbDigits`, is set to `10` to get a 10-digit number. The second parameter, `$strict`, when set to `true`, ensures that the number does not have leading zeros, which is essential for a valid 10-digit number.

This will give you a random 10-digit integer, such as `1234567890` or `9876543210`[1][4].

If you need to ensure that the number is always exactly 10 digits long and you want to include leading zeros, you can use:

php
$tenDigitNumber = str_pad($faker->randomNumber(9, true), 10, '0', STR_PAD_LEFT);

This code generates a random 9-digit number and then pads it with leading zeros to ensure it is 10 digits long.

Citations:
[1] https://laracasts.com/discuss/channels/laravel/how-can-i-get-a-10-digit-faker-random-number
[2] https://stackoverflow.com/questions/24884174/generate-random-number-in-laravel
[3] https://laracasts.com/discuss/channels/general-discussion/fakers-random-digit-unique
[4] https://fakerphp.org/formatters/numbers-and-strings/
[5] https://github.com/faker-ruby/faker/issues/237