Repository navigation
Replies: 2 comments
|
@cmtinz For a casted Example: use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class SongDataCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return SongData::from(json_decode($value, true));
}
public function set($model, string $key, $value, array $attributes)
{
return json_encode(
SongData::from($value)
->except('full_name')
->toArray()
);
}
}Then use the custom cast: class Artist extends Model
{
protected $casts = [
'song' => SongDataCast::class,
];
}Now $song->full_name;but it will not be persisted to the database. The idea is to keep computed properties as part of your application data model, and remove them only at the persistence boundary. References:
|
|
You don’t need to write a custom Solution 1: Use the
|
Uh oh!
There was an error while loading. Please reload this page.
I have a data class that has a computed property and is used as a casted field in a model. My problem, is when I persist the model, that data is also saved, which is unwanted.
Is there a way of transforming the data just at the time of saving?
All reactions