Laravel 5 how to add to $ c / $ add fields to child model class
I have several models that share some common functionality (due to their polymorphism) that I would like to insert into the ResourceContentModel class (or even a dash).
The ResourceContentModel class extends the elite model class and my individual models then extend the ResourceContentModel.
My question is about model fields like $ with, $ appends and $ touch. If I use them for any of the generic ResourceContentModel functions, then when I override them in the child model class, it overwrites the values I set in the parent class.
Looking for any suggestions on this?
For example:
class ResourceContentModel extends Model
{
protected $with = ['resource']
protected $appends = ['visibility']
public function resource()
{
return $this->morphOne(Resource::class, 'content');
}
public function getVisibilityAttribute()
{
return $this->resource->getPermissionScope(Permission::RESOURCE_VIEW);
}
}
class Photo extends ResourceContentModel
{
protected $with = ['someRelationship']
protected $appends = ['some_other_property']
THESE ARE A PROBLEM AS I LOSE THE VALUES IN ResourceContentModel
}
I have a clean way of doing this so that the child classes are not overly modified by the fact that I have an additional class in the hierarchy to collect common code.
source to share
Don't know if this will work ...
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::$this->with);
}
}
Or perhaps add a ResourceContentModel method to access the property.
class ResourceContentModel extends Model
{
public function getParentWith()
{
return $this->with;
}
}
then
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::getParentWith());
}
}
EDIT
In the constructor of the third fragment
$this->with = array_merge(['someRelationship'], parent->getParentWith());
necessary
$this->with = array_merge(['someRelationship'], parent::getParentWith());