-1

我在我的 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?我是否应该,而不是在控制器中对模型事件执行某些操作,或者是否有一种我遗漏的方法在验证之前更新唯一约束?

4

1 回答 1

1

在我的问题中,我忽略了一个事实,即 ardent 有一个方法,当您的规则中有独特的约束时updateUniques,可以使用该方法代替for。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() );
    }

    ...

}
于 2015-02-12T11:41:02.083 回答