将当前字段的值传递给 Laravel 中的自定义验证函数

Passing the value of current field to custom validation function in Laravel

我想将当前字段的值传递给我的 Laravel 项目中请求 class 中的自定义验证函数。

我试过以下方法:

public function rules()
{
    return [
        'id'=>'required',
        //'type'=>'required|in:Attachment,Audio,Book,Picture,Video',
        'type'=>['required', $this->validateFileType()],
        //'type'=>[new Enum(FileType::class)], # only available on PHP 8.1+
        'soft_price' => 'numeric|min:1000',
        'hard_price' => 'numeric|min:1000',
    ];
}

public function validateFileType($type){

    $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];

    if(in_array($type, $file_types))
        return true;
    else
        return false;
}

我收到以下错误:

"Too few arguments to function App\Http\Requests\FileUpdateRequest::validateFileType(), 0 passed in C:\xampp\htdocs..."

我该怎么做?

您必须在规则函数中传递两个参数,有关详细信息,请查看 laravel documentation

你应该看看 Custom Validation Rules

您可以使用 artisan 添加自定义规则 Class:

php artisan make:rule MyFileType

在其中,您可以访问当前值并输出自定义错误消息

public function passes($attribute, $value)
{
    $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
    
    if(in_array($value, $file_types))
        return true;
    else
        return false;
}

您可以像这样在代码中使用它:

use App\Rules\MyFileType;

public function rules()
{
    return [
        ...
        'type' => ['required', new MyFileType],
        ...
    ];
}

创建新规则:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FileTypeRule implements Rule
{
    public function passes($attribute, $value)
    {
        $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];

        if(in_array($file_types, $value))
           return true;
        else
           return false;
    }
}

在请求规则方法中使用它:

public function rules()
{
    return [
        'id'=>'required',
        'type'=>['required', new FileTypeRule()],
        'soft_price' => 'numeric|min:1000',
        'hard_price' => 'numeric|min:1000',
    ];
}