Skip to content

Repository files navigation

laravel-jsonsafe

Laravel JsonSafe

Latest Version on Packagist run-tests

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.

About

Laravel Jsonsafe For database column with standard schema validation

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages