从数据库条目生成Laravel 5规则

时间:2015-11-06 19:29:54

标签: laravel-5

我想从数据库表中的设置动态生成Laravel规则。如何解决这个问题?

protected $rules = [
    'firstname' => ['required'],
    'lastname' => ['required'],
    'email' => ['required']
];

我可以在$ rules中从数据库中执行get()吗?或者我应该创建一个创建数组的函数,如:

我开始在处理表单POST的函数中进行此操作:

private function getFormRules($slug = null) {
    $values = Value::where('element_field_id', 2)->where('value_char', $slug)->get();
    $rules_array = '';
    foreach($values as $value) {
            $rules_array .= "'".$value['form-field-name']."' => ['required'],";
        }
    }
    $rules = "[".rtrim($rules_array, ",")."]";
    return $rules;
}

然后在表单函数中我通过以下方式制定规则:

public function form($slug = null) {
    $rules = $this->getFormRules($slug);
    // then validate, if not OK, show the form with errors
    // if validated, submit form
    // etc etc etc
}

使用此函数返回的字符串是:

['email' => ['required'], 'address' => ['required'], 'lastname' => ['required'], 'firstname' => ['required'], 'phone' => ['required']]

我的主要问题是,我可以用它来验证我的表格。

0 个答案:

没有答案