-
Notifications
You must be signed in to change notification settings - Fork 28
[Proposal] Implement custom & nested casting for Eloquent Model (WIP) #1354
Comments
Also related:
(there are so many more, gave up :D ) |
Keep in mind that casts can theoretically be two-way, and we should at least make sure that our method names will not cause issues in the future. You either cast a database value to a php value, or a php value to a database value. In this case, why are you assigning a string to the properties attribute when creating a Setting, instead of assigning an instance of SettingProperties?
In my fantasy world (where the sun always shines and I'm not always bitter), that would be capable of setting the address_street, address_zipcode and address_city database fields. And reading the user from the database would combine these three columns into one Address object. |
Hi @sisve, I've started a new repo (https://github.com/ARCANEDEV/LaravelCastable) to see how far we can extend the casts feature. Any feedbacks/suggestions would be greatly appreciated 👍 NOTE: If this suggestion been rejected to be in the laravel/framework, i'll release it as a laravel package |
I would like to evolve this to a more general approach. So it would be awesome to be able to register custom casts which implement an accessor and mutator and replace the methods in the model itself by only registering them like a driver and using them in the Model::registerCastDriver('coordinates', new CoordinateAttributeCaster());
$casts = [
'location' => 'coordinates',
]; This would also make it easier for packages to provide casts.
Without messing with model core methods and forcing conflicts with multiple custom casts. In best case this also allows to pass additional information like the decimal or date cast. |
I had some cases when i need to cast some attributes to a custom type or even with nested casts.
So, i've been thinkering with an easy and useable way to acheive this.
THE ZONDA IDEA
This is the feature we love to have in our daily life:
And i have the
properties
column in thesettings
table with the following value.So we can access them like the following example:
And if you're asking what it looks like the
SettingProperties
?The
Carbon
class is also an attribute caster, but it will allows you to handle the custom casts:About the
AttributeCaster
class, it's still WIP:To Reproduce
This is the full
Setting
model class with overridden default cast attribute:And create/copy the other classes with their respective directories/namespaces:
App\Models\Casts\AttributeCaster
App\Models\Casts\SettingProperties
App\Models\Casts\Carbon
And finally in your web.php routes:
Related:
The text was updated successfully, but these errors were encountered: