Andy Noelker Andy Noelker - 1 year ago 120
PHP Question

How to lazy load a custom attribute on a Laravel model?

Is there any possible way to lazy load a custom attribute on a Laravel model without loading it every time by using the

property? I am looking for something akin to way that you can lazy load Eloquent relationships.

For instance, given this accessor method on a model:

public function getFooAttribute(){
return 'bar';

I would love to be able to do something like this:

$model = MyModel::all();

This question is not the same thing as Add a custom attribute to a Laravel / Eloquent model on load? because that wants to load a custom attribute on every model load - I am looking to lazy load the attribute only when specified.

I suppose I could assign a property to the model instance with the same name as the custom attribute, but this has the performance downside of calling the accessor method twice, might have unintended side effects if that accessor affects class properties, and just feels dirty.

$model = MyModel::all();
$model->foo = $model->foo;

Does anyone have a better way of handling this?

Answer Source

Is this for serialization? You could use the append() method on the Model instance:

$model = MyModel::all();

The append method can also take an array as a parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download