Try a simple each. Using user and posts to make it easy to understand
$user->posts->each->appends('foo');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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!
Try a simple each. Using user and posts to make it easy to understand
$user->posts->each->appends('foo');
Please or to participate in this conversation.