Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FrazeColder's avatar

Can PHP traits add values to protected values of the model

Hi,

I am using Laravel 7 and at the moment I am trying to centralize some code by using PHP traits. However, I want to have traits which e.g. also add values to the protected $attributes variable or the protected $with variable.

Why I want that? Because I want to have code reuse and not to tell every Laravel model where I use my trait to also load the relationship and add the attributes to my model. That would be quite redundant...

I already figured out a way to add values to the protected $attributes variable. However, how can I add comments to my protected $with variable?

This is the code to add values to the protected $attributes variable:

    /* Add attributes to model $appends */
    protected function getArrayableAppends()
    {
        $this->appends = array_unique(array_merge($this->appends, ['publishedComments']));

        return parent::getArrayableAppends();
    }

Kind regards

0 likes
0 replies

Please or to participate in this conversation.