Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 appends 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();
$model->loadAttribute('foo');

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?

like image 696
Andy Noelker Avatar asked Oct 11 '16 15:10

Andy Noelker


1 Answers

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

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

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

like image 197
Hammerbot Avatar answered Oct 17 '22 12:10

Hammerbot