MikaelL
MikaelL

Reputation: 414

Possible to guard columns for updates only in Laravel 4?

You have the $fillable and $guarded to protect from mass assignment. But how do I guard certain db-columns so that it's impossible to update them?

Upvotes: 1

Views: 643

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

You could override the isFillable() in your model and use the exists property to determine if the model is already in the database or not (if you're creating or updating). Also you're going to need another property to configure those attributes. Let's call it $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 still won't be mass assigned in any case. Whereas bar is mass assignable when creating a new model but not when updating one.

Upvotes: 1

Related Questions