Mutable JSON column casting for Laravel Eloquent. Supports JSON Schema validation via opis/json-schema.
You can install the package via composer:
composer require amol/laravel-jsonsafeCast 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'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 ExceptionKey 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.).
toArray() and toJson() return the underlying plain array:
$user->extras->toArray(); // ['theme' => 'dark']composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.