Skip to content

[7.x] Support returning an instance of a caster#32225

Merged
taylorotwell merged 1 commit intolaravel:7.xfrom
brendt:allow-cast-type-instances
Apr 4, 2020
Merged

[7.x] Support returning an instance of a caster#32225
taylorotwell merged 1 commit intolaravel:7.xfrom
brendt:allow-cast-type-instances

Conversation

@brendt
Copy link
Contributor

@brendt brendt commented Apr 4, 2020

See #32215 (comment)


With the addition of the Castable interface (laravel/docs#5934), it makes sense to allow direct instantiation from within a Castable::castUsing implementation. A common usecase could be something like this:

class EloquentDataTransferObject extends DataTransferObject implements Castable
{
    public static function castUsing()
    {
        return new DataTransferObjectCaster(static::class);
    }
}

Which allows a kind of "generic" cast. All classes extending EloquentDataTransferObject can now directly be used as a cast type, and will be casted to the correct implementation of EloquentDataTransferObject.

Eg.

class MyData extends EloquentDataTransferObject {
    public int $property = 1;
}

class ModelX extends Model
{
    protected $casts = [
        'data' => MyData::class,
    ];
}

@brendt brendt changed the title Support returning an instance of a caster [7.x] Support returning an instance of a caster Apr 4, 2020
@taylorotwell taylorotwell merged commit 939ba8c into laravel:7.x Apr 4, 2020
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.

2 participants