首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ardent w/ Laravel中创建可访问模型以执行脏检查的自定义验证规则

在Ardent w/ Laravel中创建可访问模型以执行脏检查的自定义验证规则
EN

Stack Overflow用户
提问于 2013-09-07 02:13:46
回答 1查看 1.1K关注 0票数 2

目标

我在Laravel中有一个名为User的Ardent模型。

我希望有一个名为confirm_if_dirty的自定义验证规则。

只有当User->password属性是脏的时,它才会运行。它预计会有一个User->password_confirmation字段。

下面是此规则可能的示例。

代码语言:javascript
复制
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在我的例子中被传入,或者模型实例是有问题的?

EN

回答 1

Stack Overflow用户

发布于 2013-10-04 15:38:21

下面是我如何在验证器函数中提供对模型的访问:

代码语言:javascript
复制
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属性的形式访问模型实例:

代码语言:javascript
复制
class CustomValidator extends Validator {

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

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18664053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档