目标
我在Laravel中有一个名为User的Ardent模型。
我希望有一个名为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在我的例子中被传入,或者模型实例是有问题的?
发布于 2013-10-04 15:38:21
下面是我如何在验证器函数中提供对模型的访问:
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!
}
}https://stackoverflow.com/questions/18664053
复制相似问题