如何在laravel nova中为一个字段添加自定义验证和消息

joy*_*joy 5 laravel eloquent laravel-5 laravel-5.2 laravel-nova

我想为 laravel nova 资源文件中的一个字段添加自定义验证。

service_idservice表中有一个 db 字段,并且我有同一张表的 nova 资源文件。在创建服务时,我想service_id从其他表中获取数据并检查数据是否存在,如果存在,那么我不想将其输入到service_id表中。

那么有人可以帮助我如何在 laravel nova 资源文件中编写自定义验证规则?

Had*_*jem 5

使用以下命令,您可以创建自定义规则类:

php artisan make:rule CustomRule
Run Code Online (Sandbox Code Playgroud)

在您的资源中的字段功能内:

Text::make('Service ID', 'service_id')->rules(new CustomRule());
Run Code Online (Sandbox Code Playgroud)

返回规则文件并在 Pass 函数内:

public function passes($attribute, $value)
{
    //You can check inside the database if your record exists
    return false; //if the rule should stop the user
    return true; //if everything is fine and you want the user to proceed.
}

public function message()
{
    return 'Return your custom error message';
}
Run Code Online (Sandbox Code Playgroud)