In Laravel 10, these validation classes were deprecated:
ImplicitRule
InvokableRule
Rule
I am trying to extend Validator by using Validator::extend() and passing a custom validation rule class, which implements new ValidationRule interface, but I cannot find any example on how to do that.
ValidationRule class has the following method:
public function validate(string $attribute, mixed $value, Closure $fail): void
Validator class has the following method:
public static function extend($rule, $extension, $message = null)
Validator::extend() method's $extension parameter requires a boolean return value, but ValidationRule validate() method returns void. Also, I don't know how instantiate $fail Closure within AppServiceProvider class;
Also, I need additional data and validator instances inside custom validation rule, but I cannot pass them.
I found ValidatorAwareRule and DataAwareRule interfaces in Laravel docs, so I have implemented them, but their implemented methods don't trigger at all.
/**
* Bootstrap any application services.
*
* @return void
* @throws ReflectionException
*/
public function boot(): void
{
Validator::extend('exists_hashid', ExistsHashid::class);
}
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Validation\Validator;
class ExistsHashid implements DataAwareRule, ValidationRule, ValidatorAwareRule
{
public function setData(array $data)
{
// This never triggers
}
public function setValidator(Validator $validator)
{
// This never triggers
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// This fails with "message": "App\Rules\ExistsHashid::validate(): Argument #3 ($fail) must be of type Closure, array given, called in /Users/milan/Sites/tabula/server/vendor/laravel/framework/src/Illuminate/Validation/Validator.php on line 1535"
}
}
It looks like this is the expected declaration of validate() method:
public function validate(string $attribute, mixed $value, array $data, Validator $validator): bool
which collides with the one implemented from the interface.
How do I put these classes together?