/    Sign up×
Bounties /Pin to ProfileBookmark

How can I add a custom attribute to a model on load in Laravel?

to post a answer
Laravel

2 Replies

Copy linkTweet thisAlerts:
@MichaelDelgadoAug 11.2022 — If I understood your question correctly, what you need here is an accessor: Link to documentation

Have in mind that this is different in Laravel 9 and previous versions, for example, In Laravel 8 it is different: Link to documentation
Copy linkTweet thisAlerts:
@hungerAug 31.2022 — using the load() method on a model is meant for loading relationships on the given model, if you'd like to load an attribute/accessor such as the custom one i have below

class Foo extends Model

function getCustomAttribute() {
return $this->column * 5;
}

you can use loadAccessors() which allows you to pass in an array of accessors/ custom attributes and will be added into the model that is returned - since custom attributes are called without the prefix of "get" and suffix of "attribute" you only need to enter the middle part of the function thanks to laravel magic

$foo->loadAccessors(['custom'])


you may also be able to use setAppends() which works the same way
$foo->setAppends(['custom'])


although the advantage of using loadAccessors() is that it can work through relationships, now the relationship "foo" will be loaded on the model "bar" as well as the custom attribute on the "foo" model


$bar->loadAccessors(['foo.custom'])


if you would always like to see the custom attribute loaded on the model, you can instead add the following to your model


class Foo extends Model

protected $appends = ['custom'];
×

Success!

Help @JacobBarker spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...