When I was working on a project recently, I realized I needed a dynamic way to validate user inputs based on different conditions. Laravel 12 makes it super easy to create custom validation rules! Let me show you a simple and clear method to build your own dynamic validation rule in Laravel 12.
Run this artisan command to generate the rule:
php artisan make:rule DynamicValidationRule
It will create a new file in app/Rules/DynamicValidationRule.php
Open the generated file and modify it like this:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class DynamicValidationRule implements Rule
{
protected $parameter;
public function __construct($parameter)
{
$this->parameter = $parameter;
}
public function passes($attribute, $value)
{
// Example: Validate based on parameter
return strlen($value) > $this->parameter;
}
public function message()
{
return 'The :attribute must be longer than ' . $this->parameter . ' characters.';
}
}
Example in your controller:
use App\Rules\DynamicValidationRule;
$request->validate([
'username' => ['required', new DynamicValidationRule(5)],
]);
This rule will ensure the username is longer than 5 characters.
You can even pass different conditions dynamically by modifying the constructor to accept more parameters.
new DynamicValidationRule($request->input('min_length'));
Creating dynamic validation rules in Laravel 12 is a powerful way to keep your code clean and reusable. With just a few lines, you can handle complex validations easily! Next time you need custom rules, just create your own class and control the logic yourself.
A validation rule in Laravel 12 ensures that user inputs meet specific criteria before saving or processing them.
You can create custom validation rules using the php artisan make:rule RuleName
command and defining your logic inside the rule.
Yes! Laravel 12 allows dynamic rules by passing parameters to your custom rule classes.
For complex scenarios, custom rules are better because they keep your controller clean and your logic organized.
By default, custom rules are stored in the app/Rules
directory.
For more detailed information, refer to the official Laravel documentation on validation.
You might also like: