Nowadays (at least in Laravel 10) here is how it worked for me..
Since Illuminate\Contracts\Validation\Rule
is depricated we now need to implement use Illuminate\Contracts\Validation\ValidationRule
.
This needs a validate
function but we can simply use the passes
function to do the actual check
<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Validator;
class IsUniqueNickname implements ValidationRule
{
public static function register(): void
{
Validator::extend('is_unique_nickname', self::class . '@passes', (new self)->message());
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
return 'Your custom message here';
}
/**
* Check if the rule passes based on the given arguments.
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes(string $attribute, mixed $value): bool
{
if ($value == 'Some Unique Nickname') { // Do some useful checks here..
return true;
}
return false;
}
/**
* Run the validation rule.
* @param string $attribute
* @param mixed $value
* @param Closure(string): PotentiallyTranslatedString $fail
* @return void
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!$this->passes($attribute, $value)) {
$fail($this->message());
}
}
}
You can "register" the custom Rule in the AppServiceProvider like this:
<?php
namespace App\Providers;
use App\Rules\IsUniqueNickname;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
IsUniqueNickname::register();
}
}
What it comes down to is this
The rule needs the passes
method to use it like this 'nickname' => ['required', 'is_unique_nickname'],
The rule needs the validate
method to use it like this 'nickname' => ['required', new IsUniqueNickname()],
Advantage of the second way is that you could give some arguments to the class to begin with and that the message can be dynamic based on the state of the rule.