Posts Learn Components Snippets Categories Tags About
/

How to Validate Password in Laravel Using Rule

To ensure that password is secure and have the right leavel of complexity you may use Laravel Password rule.

Created on Aug 10, 2021

34 views

In order to have secure Laravel authentication, you will have to make sure your application has strong password validation. To do that, you can make use of the Laravel password validation rule and you can define it by chaining the method provided by Laravel.

The minimal password validation in Laravel can be defined like below but to ensure that it's really secure you can further chain the condition to add more complexity.
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

$validator = Validator::make($request->all(), [
    'password' => ['required', 'confirmed', Password::min(8)],
]);

Available Password Methods
Below are the available methods provided by the "Password" validator and you can chain them together as necessary.
// Require at least 8 characters...
Password::min(8)

// Require at least one letter...
Password::min(8)->letters()

// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()

// Require at least one number...
Password::min(8)->numbers()

// Require at least one symbol...
Password::min(8)->symbols()

// Check if password is not compromised
Password::min(8)->uncompromised()

Secure Laravel Password Validation Rule
Finally, to build up a secure password you can define the chaining like below.
Password::min(8)
    ->letters()
    ->mixedCase()
    ->numbers()
    ->symbols()
    ->uncompromised()

Extra: Default Password Validator
Sometimes you might have multiple authentication logins available in your application, to share the password rule you can define a password default rule. To define it you can specify inside the "AppServiceProvider" and below are the code examples.
use Illuminate\Validation\Rules\Password;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Password::defaults(function () {
        $rule = Password::min(8);

        return $this->app->isProduction()
                    ? $rule->mixedCase()->uncompromised()
                    : $rule;
    });
}

Once you have defined the default then you can specify the default rule password from the controller.
'password' => ['required', Password::defaults()]

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to Validate Password in Laravel Using Rule

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More