Skip to content

Conversation

@Propaganistas
Copy link
Contributor

I often feel the need to define an accessor/mutator combination when I want certain attributes to be automatically converted from and to a dedicated value object. Since this logic is reusable across various models but not necessarily on equal named attributes, I think the most clean way to implement this kind of functionality is when custom casts can be defined.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Model::extendCasts('phoneObject', function($value) {
            // First closure is the accessor closure.
            return new Phone($value);
        }, function($value) {
            // Second closure is the mutator closure.
            return $value instanceof Phone ? $value->getNormalizedValue() : $value;
        });
}

class SomeModel extends Model
{
    protected $casts = [
        'someAttribute' => 'phoneObject',
    ];
}

Looking forward to your feedback.

@tillkruss tillkruss changed the title Define custom attribute casts [5.7] Custom Eloquent attribute casts May 5, 2018
@sisve
Copy link
Contributor

sisve commented May 6, 2018

  1. Would this support something like User::where('phone', '=', $phoneObject)->get()?
  2. Can this handle value objects that is composed of more than one attribute?

@taylorotwell
Copy link
Member

If I can't mutate the objects and then call ->save() and parent object and have those changes be reflected in the database I'm not very interested. Even then everyone argued about it to the point I lost interest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants