Създаване на персонализирано правило за валидиране в Ardent w/ Laravel, което има достъп до модела, за да извърши мръсна проверка

Цел

Имам модел на Ardent, наречен User в Laravel.
Искам да имам персонализирано правило за валидиране, наречено confirm_if_dirty.

Това ще се изпълнява само ако атрибутът User->password е мръсен. Очаква се да има поле User->password_confirmation.

По-долу е даден пример как може да изглежда това правило.

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;

});

Въпрос

Как мога да направя така, че $model в моя случай да се предава или е въпросният екземпляр на модела?


person Mark Evans    schedule 06.09.2013    source източник


Отговори (1)


Ето как правя, за да осигуря достъп до модела във функция за проверка:

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']);
    }

}

Сега е възможно да имате достъп до екземпляра на модела като атрибута model в валидатора:

class CustomValidator extends Validator {

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

}
person J. Bruni    schedule 04.10.2013
comment
Значи $this-›attributres става $this-›data в валидатора? - person Mark Evans; 05.10.2013
comment
да Ardent изпраща данните за модела към валидатора (вижте тук). Можете да видите как собственият валидатор на Laravel го използва (вижте тук). - person J. Bruni; 05.10.2013