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

dsampaolo's avatar

Dynamic append on Model

Hi everyone,

I've got a Laravel website with a few models. On some of them, I defined some custom attributes, and I'd like to eager load them.

For example, I have a Website model with an Earnings attribute, defined in Website::getEarningsAttribute(). This attributes needs a few heavy SQL requests, and isn't needed on all occurrences of the model. So, I'd like to eager load it, as I would do with relations, via

$website = Website::where('foo','bar')->with('my_relation')->get();

I tried to do :

$website = Website::where('foo','bar')->append('my_attribute')->get();

but it doesn't exist.

I am fully aware that I can use the $appends attribute in my model file, but it would perform the heavy requests even when it's not needed.

Any insight would be appreciated. Have a good day ! :)

0 likes
1 reply
dsampaolo's avatar

One possible way of doing it :

$websites = Website::where('foo', 'bar')->get();
foreach($websites as $website) {
    $website->append('earnings');
}

it works... but it would be way cleaner to add my "custom appends" directly onto the query builder.

1 like

Please or to participate in this conversation.