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

andrewblackwell's avatar

Append custom attribute to related model on runtime

I am looking for a way, or even wondering if it is at all possible, to append a custom attribute to a related model when eager-loading it on runtime.

I know that one can append a custom attribute to the "root" model at runtime with the ->appends('custom_attribute') method, and that one can selectively choose which model attributes should be displayed on a related model by writing ->with('related_model:colum_a,column_b'), but this only works for columns that actually exist on the database, and not for custom attributes, so ->with('related_model:custom_attribute_on_related_model') will not work.

Is there any shorthand solution similar to above that will allow this, or even a more verbose one, albeit still eager loading the models with '->with()'?

What I want to avoid / what isn't an option: appending the custom attribute on the model (I don't always want it to be appended, as it references related models and in certain circumstances would bring down the performance necessarily, especially on lists)

Is there a way, or would I have to drop Laravel's eager loading / model relationship approach and query and attach the related models in the controller to be able to append custom attributes like this?

Thanks in advance for any pointers!

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try a simple each. Using user and posts to make it easy to understand

$user->posts->each->appends('foo');
3 likes
rahulshinde19's avatar

@Sinnbeck This will throw error you have to use setAppends instead of appends

$user->posts->each->setAppends(['foo']);
1 like
andrewblackwell's avatar

Thank you, @sinnbeck - that solved my problem!

Funnily, ->appends() threw an error message, saying that the method was not available on the model (I don't know why, though; it usually is), but deep-diving the source code I found the ->setAppends() method, so the following worked (using your example):

$user->posts->each->setAppends(['foo']);

Mange tak for hjælpen :-)

1 like
Sinnbeck's avatar

@andrewblackwell det var så lidt

Yeah that's the problem with coding on you phone from memory. Great that you got it working

1 like
andrewblackwell's avatar

@Sinnbeck I found the issue now - the method is ->append() not ->appends() – I keep making the same mistake (probably because it's $appends on the model). Help much appreciated!

1 like

Please or to participate in this conversation.