2

I have a model containing some $fillable, mass-assignable fields.

However, some of the fields should only be mass-assignable when creating, not when updating.

What is the correct method of doing this?

Thanks.

Qar
  • 1,746
  • 3
  • 17
  • 24

2 Answers2

0

Potentially you could try overriding getFillable on the model.

public function getFillable()
{
    if ($this->exists) {
        // modify the fillable or return a different fillable array
    }

    return $this->fillable;
}
lagbox
  • 48,571
  • 8
  • 72
  • 83
  • Thanks for your reply. I was thinking of this - but is it the right way? It feels a bit dodgy overriding stuff, instead of defining the situational fillables to start with. (If that's even possible). – Qar Jan 15 '16 at 15:17
  • I was also thinking about just making an impossible validation rule for the exception fields, that would work, be easy to do, but feels dodgy as well. – Qar Jan 15 '16 at 15:20
  • there might be other places you could override or in a different way. with this approach you could define a second fillable array and return that, which would make it conditional. – lagbox Jan 15 '16 at 15:20
0

If you don't want to overload getFillable()

class MyModel extends Eloquent
{
    public function create(array $attributes = []) {
        $this->fill($attributes);
        $this->protected_attriute = $attribute['protected_attribute'];

        return $this;
    }
}
Sturm
  • 4,105
  • 3
  • 24
  • 39