2

Goal

I have an Ardent model called User in Laravel.
I want to have a custom validation rule called confirm_if_dirty.

This would only run if the User->password attribute is dirty. It would expect there to be a User->password_confirmation field.

Below is an example of how this rule might look.

Validator::extend('confirm_dirty', function($attribute, $value, $parameters) use($model)   
{
//If field is not dirty, no need to confirm.
if($model->isDirty("{$attribute}")){

    //Confirmation field should be present.
    if(!$model->__isset($attribute."_confirmation")){
        return false;
    }
    //Values should match.
    $confirmedAttribute = $model->getAttribute($attribute."_confirmation");
    if( $confirmedAttribute !== $value){
        return false;
    }
    //Check to see if _confirmation field matches dirty field.
}

return true;

});

Question

How can I make it so that $model in my case is passed in or is the model instance in question?

Laurence
  • 58,936
  • 21
  • 171
  • 212
Mark Evans
  • 810
  • 10
  • 18

1 Answers1

1

Here is how I am doing to provide access to the model in a validator function:

class CustomModel extends Ardent {

    public function __construct(array $attributes = array())
    {
        parent::__construct($attributes);

        $this->validating(array($this, 'addModelAttribute'));
        $this->validated(array($this, 'removeModelAttribute'));
    }

    public function addModelAttribute()
    {
        $this->attributes['model'] = $this;
    }

    public function removeModelAttribute()
    {
        unset($this->attributes['model']);
    }

}

Now, it is possible to have access to the model instance as the model attribute in the validator:

class CustomValidator extends Validator {

    protected function validateConfirmDirty($attribute, $value, $parameters)
    {
        $this->data['model'];   // and here is the model instance!
    }

}
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
  • So $this->attributres becomes $this->data in the validator? – Mark Evans Oct 04 '13 at 22:02
  • Yes. Ardent sends the model data to the validator ([see here](https://github.com/laravelbook/ardent/blob/master/src/LaravelBook/Ardent/Ardent.php#L507)). You can look at how Laravel's own Validator uses it ([see here](https://github.com/laravel/framework/blob/master/src/Illuminate/Validation/Validator.php#L501)). – J. Bruni Oct 05 '13 at 07:02