如何使用Laravel Form Request验证数组的键?

时间:2020-11-10 23:27:53

标签: laravel forms validation request

验证请求中的参数应采用以下格式的正确方法是什么:具有确定值的键和布尔值的数组

"countries" => array:2 [
  "usa" => true
  "canada" => true
]

在我的表单请求中,我有以下规则:

public function rules()
{
    return [
        'countries' => ['bail', 'array'],
        'countries.*' => ['string', new ValidateCountries],
        'countries.*.' => ['boolean'],
    ];
}

我的ValidateCountries passes()方法:

public function passes($attribute, $value)
{
    $countries = ["usa", "canada", "uk", "france"];
    return in_array(strtolower($value), $countries);
}

1 个答案:

答案 0 :(得分:1)

通过访问$attribute参数而不是$value来获得它。很简单,但是我的大脑却炸了。

public function passes($attribute, $value)
{
    $attribute = explode(".", $attribute)[1];
    $countries = ["usa", "canada", "france", "uk"];
    return in_array(strtolower($attribute), $countries);
}