To customize the password rules in Laravel Fortify, you can follow these steps:
1. Create a custom `PasswordValidationRules` trait:
- Create a new file called `PasswordValidationRules.php` in your `app/Actions/Fortify` directory.
- Define your custom password validation rules in the `passwordRules` method.
php
<?php
namespace App\Actions\Fortify;
use Laravel\Fortify\Rules\Password;
trait PasswordValidationRules
{
/**
* Get the validation rules used to validate passwords.
*
* @return array
*/
protected function passwordRules()
{
return ['required', 'string', new Password, 'confirmed'];
}
}
2. Use the custom `PasswordValidationRules` trait:
- Open your `CreateNewUser` class located in `app/Actions/Fortify`.
- Import the `PasswordValidationRules` trait and use it in your class.
php
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(), // Use the custom password rules
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
// ...
}
}
3. Customize the password rules:
- In the `passwordRules` method of the `PasswordValidationRules` trait, define your desired password rules.
- You can use the built-in `Password` rule provided by Fortify or create your own custom rules.
php
protected function passwordRules()
{
return ['required', 'string', new Password, 'confirmed', 'min:8', 'max:20'];
}
In this example, we added additional rules to enforce a minimum length of 8 characters and a maximum length of 20 characters for the password.
By following these steps, you can customize the password validation rules used by Fortify during the registration process. You can further enhance the rules based on your application's specific requirements.
Remember to clear the configuration cache after making changes to the password rules:
bash
php artisan config:clear
This ensures that the updated password rules are properly loaded by Fortify.
Citations:[1] https://laracasts.com/discuss/channels/laravel/laravel-fortify-post-request-to-reset-password-not-working
[2] https://laracasts.com/discuss/channels/laravel/laravel-fortify-password-reset-login-issue
[3] https://github.com/laravel/fortify/actions/runs/8832562441/job/24250119062
[4] https://www.youtube.com/watch?v=CLsyHP7x0N0
[5] https://laravel.com/docs/11.x/fortify