播种验证阵列

Seeding validation array

我通过播种机提出了很多问题。我做的格式是这样的

DB::table('questions')->insert([
    'name' => 'questionOne',
    'rule' => 'nullable|max:50|regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/'
]);

我在此提供一个字段名称和一个验证规则。我注意到在应用上述规则时,验证会失败,并显示

preg_match(): No ending delimiter '/' found

我做了一些研究,发现

When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

按照推荐,我把播种机改成了这个

DB::table('questions')->insert([
    'name' => 'questionOne',
    'rule' => ['nullable|max:50|regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/']
]);

但是,当我尝试使用上面的方法播种时,出现了数组到字符串的转换错误。我应用验证的方式是这样的

$rules = [];
$questions = Question::all();
foreach ($questions as $question) {
    if (!empty($question->rule)) {
        $rules["questions.{$question->id}"] = $question->rule;
    }
}

$this->validate($request, $rules);

有什么方法可以让上面的正则表达式工作吗?需要注意的一点是只有少数问题有这个正则表达式,如果这很重要?

谢谢

When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

这是指传递给$this->validate$rules变量;您的正则表达式模式包含一个竖线字符 |,它会干扰 Laravel 在内部将规则字符串拆分为数组的能力。

使用管道分隔符以字符串格式存储规则也会让您难以在从数据库检索时将它们拆分为数组。我建议将它们存储为类似描述的结构,例如 JSON,这将使您的播种机:

DB::table('questions')->insert([
    'name' => 'questionOne',
    'rule' => json_encode([
        'nullable',
        'max:50',
        'regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/'
    ])
]);

和验证:

$rules = [];
$questions = Question::all();
foreach ($questions as $question) {
    if (!empty($question->rule)) {
        $rules["questions.{$question->id}"] = json_decode($question->rule, true);
    }
}

$this->validate($request, $rules);

您还想在 questions table 迁移中将 rule 列类型更改为 JSON。

为了进一步简化代码,您可以使用 Laravel 的 attribute casting 功能,该功能声称可以为您处理 json_encode/json_decode:

protected $casts = [
    'rule' => 'array',
];