DEV Community

Yasser Elgammal
Yasser Elgammal

Posted on • Updated on

Generate Random Password in Laravel

In Laravel, you can generate a random password using the password() helper function provided by the Illuminate\Support\Str class.

This function generates a secure password that is 32 characters long by default.

To use this function, you need to import the Illuminate\Support\Str class at the top of your PHP file:

use Illuminate\Support\Str;
Enter fullscreen mode Exit fullscreen mode

Once you have imported the Str class, you can call the password() method to generate a random password:

$password = Str::password();
Enter fullscreen mode Exit fullscreen mode

By default, the generated password will be 32 characters long and will include letters, numbers, and symbols. However, you can customize the behavior of the password() function by passing in up to five parameters:

  1. Length: This parameter specifies the length of the password you want to generate. By default, the length is set to 32 characters.

  2. Letters: This parameter determines whether or not to include letters in the generated password. By default, letters are included.

  3. Numbers: This parameter determines whether or not to include numbers in the generated password. By default, numbers are included.

  4. Symbols: This parameter determines whether or not to include symbols in the generated password. By default, symbols are included.

  5. Spaces: This parameter determines whether or not to include spaces in the generated password. By default, spaces are not included.

You can customize the behavior of the password() function by passing in the desired values for each of these parameters.

For example, if you want to generate a password that is 16 characters long and only includes letters and numbers, you can call the password() function like this:

$password = Str::password(16, true, true, false, false);
Enter fullscreen mode Exit fullscreen mode

This will generate a random password that is 16 characters long and includes only letters and numbers.

Function accept first parameter as Integer and other parameters as boolean Which mean you can use true or false to include it to your returned result.

Top comments (0)