Laravel

Laravel Eloquent: Custom Casts

December 24, 2025 1 min read 78 views

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

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

Access Naturally

$post->options = ['featured' => true];
$post->save();
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!