✨
Snippets
Laravel Snippet: Custom Validation Rules
By Mohd Baquir
Qureshi
•
When Laravel's built-in validation rules aren't enough, don't stuff custom logic into your controllers. Instead, create an invokable Rule object.
Generating the Rule
php artisan make:rule Uppercase
The Snippet
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Uppercase implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (strtoupper($value) !== $value) {
$fail('The :attribute must be completely uppercase.');
}
}
}
How to Use It
You can now use this rule inside any Form Request or Controller validation array.
use App\Rules\Uppercase;
$request->validate([
'company_code' => ['required', 'string', 'size:6', new Uppercase],
]);