laravel / ideas

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

[Proposal] Add custom casting for eloquent model #2014

Closed johnylemon closed 4 years ago

johnylemon commented 4 years ago

Long story short

Many times I needed to cast database column value to specific data format or some object instance. Doing this by creating getFooAttribute|setFooAttribute methods can be cumbersome especially if same casting logic have to be used within few models or even more widely within application.

To achieve that I've created really simple package that should achieve that https://github.com/johnylemon/laravel-cast

Goals:

Coding time

The Laravel/Lumen logic for castAttribute/setAttribute are written nearly perfectly for this functionality (my package duplicates only one condition (https://github.com/johnylemon/laravel-cast/blob/7d2ec1cf060535451953237b45df761825649116/src/Traits/CustomCasts.php#L81 to keep compatibility)

The problem is with the getDirty method which have to be overwritten to achieve some additional logic (https://github.com/johnylemon/laravel-cast/blob/7d2ec1cf060535451953237b45df761825649116/src/Traits/CustomCasts.php#L136)

To achieve possibility to create custom casts in totally user-defined way some proxy class is needed (idea of "Casts"). This proxy class should define logic behind getting and storing data (reading from database, then storing to the database). Cause this data mostly is stored as json, the default set method just json_serialize given data.

Summary

I think this functionality may be written easily (maybe not this way, but that's some idea, dont you think?). No problem to create a fork and pull request.

staudenmeir commented 4 years ago

Take a look at this upcoming feature: https://github.com/laravel/framework/pull/31035

johnylemon commented 4 years ago

@staudenmeir oh, i missed it! I'll take a look, hope this will be ready asap ;-)