indexis's avatar

How to reuse $fillable in child model?

I am trying to reuse some Vehicle model $fillable fields in its children (bike, car, truck). I tried using __construct but I don't know how to get $attribute values inside model to pass it to parent classes...

0 likes
4 replies
crnkovic's avatar

What? $fillable is protected class property which means any classes that inherit the parent have access to it. Not sure what you're talking about.

indexis's avatar

Hi @crnkovic. I understand that $fillable is protected. I also understand that setting $fillable in child model will overwrite the parent's $fillable.

I tried using __construct in child model to append data to parent $fillable:

// child model extending parent model
public function __construct($attributes = [])
{
    $fillable = [ 'child_specific_field' ];
    $this->fillable = array_merge($fillable, $this->fillable);
    parent::__construct($attributes)
}

Note that parent expects $attributes and not $fillable. I don't know how to get attribute values from child model.

Matthais's avatar

Did you ever find an answer for this? I had two child classes with one extra field each to go into $fillable compared to the parent.

aarontharker's avatar

I know this is an old post but in case anyone comes accross it like I did you can use the following to extended fillable or casts arrays.

public function __construct($attributes = [])
{
    $this->mergeFillable([ 'child_specific_field' ]);
    $this->mergeCasts(['castable_value' => 'integer']);
    parent::__construct($attributes);
}
1 like

Please or to participate in this conversation.