可以仅在Laravel 4中保护列的更新?

时间:2015-03-04 10:02:19

标签: php laravel laravel-4 eloquent

您拥有$fillable$guarded以防止群发分配。但是,如何保护某些db-column,以便无法更新它们?

1 个答案:

答案 0 :(得分:1)

您可以覆盖模型中的isFillable()并使用exists属性来确定模型是否已存在于数据库中(如果您正在创建或更新)。此外,您还需要另一个属性来配置这些属性。我们称之为$guardedForUpdate

protected $guarded = ['foo'];
protected $guardedForUpdate = ['bar'];

public function isGuardedForUpdate($key){
    return in_array($key, $this->guardedForUpdate) || $this->guardedForUpdate == array('*');
}

public function isFillable($key){
    if($this->exists && $this->isGuardedForUpdate($key)){
        return false;
    }
    return parent::isFillable($key);
}
在任何情况下,

foo仍然不会被批量分配。而bar在创建新模型时是可分配的,而在更新模型时则不是。