laravel / ideas

Issues board used for Laravel internals discussions.
939 stars 28 forks source link

appends using __get() #2147

Open mblaney opened 4 years ago

mblaney commented 4 years ago

I have a model that sets an appends array to provide custom attributes. This model has a __get() method so it can return these attributes directly. However when my model is serialized, laravel is looking for get*Attribute methods on my model to provide these attributes. Instead of writing these methods it would be great if laravel could try accessing the attribute first.

For example I'm writing public function getFooAttribute() { return $this->foo; } but it seems like it should be possible to not write that function at all?

ryangjchandler commented 4 years ago

Laravel also handles the __get() stuff too so I assume you're calling parent::__get($name) from your model's overwritten implementation. Just moved your custom attributes to accessors getFooAttribute() since that it one of their main applications.

mblaney commented 4 years ago

hi @ryangjchandler yes I'm calling parent::__get($name) when I know the attribute is on the model. My custom attributes are dynamic so I can't explicitly list them all in accessor methods. The only time I want to list some of them is in the appends array, at which point I can create the accessor methods, but it's not necessary to create them to access those custom attributes.