Validating unique constraints in Laravel using the Ardent validation package

286 views Asked by At

I am using Ardent in my Laravel application to provide record validation. Ardent uses a static $rules variable in your model to store your validation information, like so:

class Project extends Ardent{

    public static $rules = array
    (
        'name'        => 'required|max:40',
        'project_key' => 'required|max:10|unique:projects',
    );

}

Ardent will use these same rules on any saving event, however the unique:projects rule requires a third parameter upon updating a record so that it doesn't validate against the current record. I would normally do this in my controller like so:

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

    ...

}

To cut down on the amount of duplicated code I have moved the code for identifying if the record exists and error handling for when it doesn't to another class method that sets $this->project to the current project but now updating the models static $rules property is problematic because the below cant work:

...

    public function update( $id ){

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

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

        ...

    }

...

How would you go about updating the static $rules? Should I, rather than doing so in the controller do something on a model event or is there a method in ardent that I am missing that updates the unique constraints before validation?

1

There are 1 answers

0
carbontwelve On BEST ANSWER

It looks like in my question, that I overlooked the fact that ardent has a updateUniques method, which is to be used in place of update for when you have unique constraints in your rules. Therefore my initial code example becomes:

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

    ...

}