使用 Ardent 验证包验证 Laravel 中的唯一约束

Validating unique constraints in Laravel using the Ardent validation package

我在 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() );
    }

    ...

}

为了减少重复代码的数量,我已将用于识别记录是否存在以及记录不存在时的错误处理的代码移至另一个 class 方法,该方法将 $this->project 设置为当前项目但现在更新模型静态 $rules 属性 是有问题的,因为以下无法工作:

...

    public function update( $id ){

        if ( ! $this->identifyProject( $id ) ){
            return $this->redirectOnError;
        }

        $this->project::$rules['project_key'] += ',' . $this->project->id;

        ...

    }

...

您将如何更新静态 $rules?我应该而不是在控制器中这样做对模型事件做一些事情,或者是否有一种我遗漏的方法在验证之前更新唯一约束?

在我的问题中,我似乎忽略了一个事实,即 ardent 有一个 updateUniques 方法,当您的规则中有独特的约束时,该方法将用于代替 update .因此我的初始代码示例变为:

class ProjectController{

    ...

    public function update( $id ){

        if ( ! $this->identifyProject( $id ) ){
            return $this->redirectOnError;
        }

        $this->project->fill(Input::only(array('name','project_key')));

        if( $this->project->updateUniques() )
        {
            return Redirect::route('project.edit', $this->project->id)
                ->with('success', 'Your changes have been saved.');
        }
        return Redirect::back()
            ->withErrors( $this->project->errors() );
    }

    ...

}