我在我的 Laravel 应用程序中使用Ardent来提供记录验证。Ardent 在模型中使用静态$rules
变量来存储验证信息,如下所示:
class Project extends Ardent{
public static $rules = array
(
'name' => 'required|max:40',
'project_key' => 'required|max:10|unique:projects',
);
}
Ardent 将在任何保存事件上使用这些相同的规则,但是该unique:projects
规则在更新记录时需要第三个参数,以便它不会针对当前记录进行验证。我通常会在我的控制器中这样做:
class ProjectController{
...
public function update( $id ){
$record = $this->projects->findById($id);
$record::$rules['project_key'] += ',' . $record->id;
if( $record->update(Input::get(array('name','project_key'))) )
{
...
}
return Redirect::back()
->withErrors( $record->errors() );
}
...
}
为了减少重复代码的数量,我将用于识别记录是否存在的代码以及当它不存在时的错误处理移动到另一个设置$this->project
为当前项目但现在更新模型静态$rules
属性的类方法是有问题的,因为以下无法工作:
...
public function update( $id ){
if ( ! $this->identifyProject( $id ) ){
return $this->redirectOnError;
}
$this->project::$rules['project_key'] += ',' . $this->project->id;
...
}
...
您将如何更新静态$rules
?我是否应该,而不是在控制器中对模型事件执行某些操作,或者是否有一种我遗漏的方法在验证之前更新唯一约束?