Generating random strings is very common for tokens, random passwords, etc. Let's see what Laravel helpers and native PHP functions we can use for this.
1. str()->random()
The most popular and one of the oldest helpers to generate a random string.
str()->random();
The default length output will be similar to this:
NmLj2RhDdnrXyzbg
Notice:
You can also provide the number of characters to generate:
str()->random(5);// Generates: "w9RUI"
Link to the documentation.
2. str()->password()
Laravel has a helper that generates a secure, random password of a given length.
By default, passwords are 32 characters long and consist of a combination of letters, numbers, symbols, and spaces.
str()->password() // Generates something like this:// ;HnM1O$]{8fF7yL7/obYaay(LGdPYr<b
Link to the documentation.
If you take a look at the Laravel source code, you may find more parameters to this function:
public static function password( $length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false) { /* ... */ }
So, experiment with true/false values for these parameters and see what happens.
3. Faker
Laravel have a fake()
helper which resolves to a Faker package. With the help of a faker, you can generate various things.
The asciify()
or regexify()
methods can be used to generate a random string using faker. To generate eight characters, random string usage could be similar to:
fake()->asciify('********'); // j!}IwNl0
fake()->regexify('[A-Za-z0-9]{8}') // jbVrK8JV
The randomNumber()
method could be used to generate a random number.
fake()->randomNumber(); // 28041
Link to the documentation.
4. str()->mask()
If you want to hide some characters in the generated string, you can do it with str($string)->mask()
. Let's combine it with Faker from above.
str(fake()->creditCardNumber())->mask("*", -4); // 455688158327****
Link to the documentation.
5. PHP Functions
If you don't want to use Laravel helpers or can't because you're using an older version where some helpers don't exist, you can use native PHP functions.
To generate a random string, the uniqid()
can be used.
By default, the returned string will be 13 characters long.
uniqid() // 664da16a1eb3b
Another option is to combine random_bytes()
and bin2hex()
PHP functions to generate a 20 character string.
bin2hex(random_bytes(10)); // f81b40db75c0697057a8
For a random number, the mt_rand()
could be used. The default minimum value is zero, and the maximum value is generated by mt_getrandmax
.
mt_rand(); // 511137210 mt_rand(10, 69); // 54
We also have more in-depth related tutorials for PREMIUM members:
- Laravel String Helpers: 16 Open-Source Examples
- String functions are also in this course: PHP for Laravel Developers
No comments or questions yet...