tighten / parental

Use single table inheritance in your Laravel app
MIT License
1.36k stars 98 forks source link

Use parent's fillables in children models #77

Closed litvinjuan closed 1 year ago

litvinjuan commented 4 years ago

When you create a parent model that has some fillable attributes and later have a child model that extends that, the child model needs to duplicate its parent's fillable attributes. In the following example, a User has a name and email, and a spy is a type of user that also has a secret_spy_id. Currently, if I do Spy::create(['name' => 'MikeSpy' ...]), I will get an exception about the name and email NOT NULL constraints being violated. This is, because Spy does not recocnize name or email as fillable attributes, and thus does not populate the fields or reflect that to the database. The following are the example classes:

class User extends Model {
    use HasChildren;

    protected $fillable = [
        'name',
        'email',
    ];
}
class Spy extends User {
    use HasParent;

    protected $fillable = [
        'secret_spy_id',
    ];
}

The above won't work unless we do the following:

class Spy extends User {
    use HasParent;

    protected $fillable = [
        'name',
        'email',
        'secret_spy_id',
    ];
}

I imagine fixing this by adding a method in HasParent that overrides Model::getFillable() and returns a merge of $this->fillable and the parent's getFillable() method. This method would look like this:

public function getFillable()
{
    $parentFillable = (new ReflectionClass($this))->getParentClass()->newInstance()->getFillable();
    return array_merge($this->fillable, $parentFillable);
}
litvinjuan commented 4 years ago

I created a PR for this so the code can be more easily visualized and/or tested. I did not yet add any tests, as I'd rather first finalize the feature, and then discuss the best testing scenarios to cover in the Unit Tests. Pull Request

AlastairDewar commented 4 years ago

Thanks @litvinjuan for your work.

I came across this ticket after noticing the same behaviour when using $hidden.

It looks like this will also apply to $guarded, $visible and $appends as well.

mattstauffer commented 1 year ago

Hey friends! The team at Tighten has taken Parental back over and we're re-opening the issue tracker, but to give us a clean slate, I'm going to close all old issues that remain from when Caleb closed the issue tracker in 2020. If this is still an outstanding concern with the latest version of Parental, please feel free to open a new issue referencing this one.

Thank you!