A new Password Rule object is now included in Laravel v8.39, thanks to the efforts of Nuno Maduro. The Password object has a fluent API for common password requirements as well as compromised passwords:
Coming to @laravelphp: Password Rule Object. 🔒
— Nuno Maduro (@enunomaduro) April 23, 2021
This rule object allows to easily customise the password complexity requirements. You may also ensure the password has not been compromised in data leaks by using the `uncompromised()` method. 🔥
🔗 https://t.co/eedKLQuZwp. pic.twitter.com/OBEyliQ7gw
Originally released in Laravel 5.5, custom validation rule objects offer a fluent alternative to string-based rules. In its simplest form, the Password
rule object replaces string-based validation rules:
1<?php 2 3// String-based 4$request->validate([ 5 'password' => 'required|string|confirmed|min:8', 6]); 7 8// Using the Password rule object 9$request->validate([10 'password' => ['required', 'confirmed', Password::min(8)],11]);
In addition to replacing string rules with a fluent password rule object, the custom password rule object includes built-in methods for ensuring strong passwords:
1<?php 2 3$request->validate([ 4 'password' => [ 5 'required', 6 'confirmed', 7 Password::min(8) 8 ->mixedCase() 9 ->letters()10 ->numbers()11 ->symbols()12 ->uncompromised(),13 ],14]);
Never write custom regex logic for typical scenarios such as requiring mixed-case, letters, symbols, etc. The cherry on the top is the uncompromised()
method which checks the password against a verification API to see if the password appears in data leaks. The release will ship with a NotPwnedVerifier implementation which uses the Have I Been Pwned API.
In addition to this excellent new custom validation object, Pull Request #36960 contains some good examples of using Laravel to test API calls and validation.
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.