Laravel Eloquent: Custom Casts

Create custom attribute casts to transform data automatically.

1 min readLaravelاقرأ بالعربية

Create custom casts:

Define Cast

class Json implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

Use in Model

php
protected $casts = [
    'options' => Json::class,
];

Access Naturally

php
$post->options = ['featured' => true];
$post->save();
All articles

Keep reading