novius/laravel-json-casted

A package to cast json fields, each sub-keys is castable
6,834 1
Install
composer require novius/laravel-json-casted
Latest Version:1.3.0
PHP:>=8.2
License:AGPL-3.0-or-later
Last Updated:May 12, 2026
Links: GitHub  ·  Packagist
Maintainer: novius

Laravel Json Casted

Novius CI Packagist Release License: AGPL v3

Introduction

A package to cast json fields, each sub-keys is castable

Requirements

  • PHP >= 8.2
  • Laravel >= 10.0

Installation

You can install the package via composer:

composer require novius/laravel-json-casted

If you use laravel-ide-helper, add ModelHasJsonWithCastsHook in its configuration file :

    'model_hooks' => [
        // ...
        \Novius\LaravelJsonCasted\Hooks\ModelHasJsonWithCastsHook::class,
    ],

Usage

Define casts by a method

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Novius\LaravelJsonCasted\Services\JsonCasted;

class Post extends Model {

    protected $casts = [
        'extras' => JsonCasted::class.':getExtrasCasts',
    ];
    
    public function getExtrasCasts(): array
    {
        return [
            'date' => 'date:Y-m-d',
        ];
    }
}

Define casts by a class

namespace App\Casts;

use Novius\LaravelJsonCasted\Services\JsonCasted;

class Extras extends JsonCasted {

    protected static array $casts = [
        'date' => 'date:Y-m-d',
    ];
}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Casts\Extras;

class Post extends Model {

    protected $casts = [
        'extras' => Extras::class,
    ];
}

Use casted field


    $model = Post::first();
    // $model->extras is now a Fluent instance 
    // $model->extras->date is a now Carbon class 
    $model->extras->date->lt(now());

CS Fixer

Lint your code with Laravel Pint using:

composer run cs-fix

Licence

This package is under GNU Affero General Public License v3 or (at your option) any later version.

Related Packages

nilportugues/serializer-eloquent

Eloquent Driver for NilPortugues Serializer outputting valid API responses in JS...

36,591 5
cviebrock/eloquent-typecast

Trait for Eloquent models to force type-casting on retrieved values

73,014 24
darrylkuhn/dialect

Provides JSON datatype support for the Eloquent ORM

245,300 126
ngmy/eloquent-serialized-lob

Eloquent Serialized LOB is a trait for Laravel 5 Eloquent models that allows Ser...

2,273 1