amol / laravel-jsonsafe
Mutable JSON column casting for Laravel Eloquent
Requires
- php: ^8.3
- illuminate/contracts: ^11.0||^12.0||^13.0
- opis/json-schema: ^2.6
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^3.10
- laravel/legacy-factories: ^1.4
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.0.0||^10.0.0||^9.0.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-arch: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
This package is auto-updated.
Last update: 2026-08-22 10:38:40 UTC
README
Mutable JSON column casting for Laravel Eloquent. Supports JSON Schema validation via opis/json-schema.
Installation
You can install the package via composer:
composer require amol/laravel-jsonsafe
Usage
Basic casting
Cast a JSON column to JsonSafe in your model:
use Amol\LaravelJsonSafe\JsonSafe; class User extends Model { protected $casts = [ 'extras' => JsonSafe::class, ]; }
Read and write nested keys directly — changes persist on save():
$user->extras['theme'] = 'dark'; $user->save(); $user->extras['theme']; // 'dark'
JSON Schema validation
Define a public schemaOf{Key}() method on your model to enable validation. The column key is converted to StudlyCase and prefixed with schemaOf (e.g., preferences → schemaOfPreferences()).
use Amol\LaravelJsonSafe\JsonSafe; class User extends Model { protected $casts = [ 'preferences' => JsonSafe::class, ]; public function schemaOfPreferences(): array { return [ 'type' => 'object', 'properties' => [ 'appearance' => [ 'type' => 'object', 'properties' => [ 'theme' => [ 'type' => 'string', 'enum' => ['light', 'dark', 'system'], ], 'fontSize' => [ 'type' => 'integer', 'minimum' => 10, 'maximum' => 24, ], ], ], ], ]; } }
If the data violates the schema, an Exception is thrown before the database write:
$user->preferences['appearance']['theme'] = 'invalid'; $user->save(); // throws Exception
Key mapping rules:
preferences→schemaOfPreferences()my_column→schemaOfMyColumn()UPPERCASE→schemaOfUppercase()
Columns without a schema method are not validated.
Schemas follow the JSON Schema standard via opis/json-schema. You can use any supported keywords (type, properties, enum, required, minimum, maximum, pattern, etc.).
Serialization
toArray() and toJson() return the underlying plain array:
$user->extras->toArray(); // ['theme' => 'dark']
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
License
The MIT License (MIT). Please see License File for more information.