Laravel Nova field for displaying JSON schema data. Inspired by nsavinov/nova-json-schema-field.
You can install the package into a Laravel app that uses Nova via composer:
composer require rsubr/nova-json-schema-field
In the Laravel Model:
use Illuminate\Database\Eloquent\Casts\AsCollection;
protected $casts = [
'details' => AsCollection::class,
];
// NovaJsonSchemaField does not like empty JSON, so use an empty placeholder
protected $attributes = [
'details' => '{"_": ""}',
];
In the Nova resource:
use Rsubr\NovaJsonSchemaField\NovaJsonSchemaField;
public function fields(Request $request)
{
return [
// ...
NovaJsonSchemaField::make('Details')
->jsonSchema($this->loadSchema())
->rules('json'),
];
}
private function loadSchema(): array
{
$schema = <<<SCHEMA
{
"type": "object",
"required": [
"event_name",
"level",
"start_date",
"duration"
],
"properties": {
"event_name": {
"description": "Event Name"
},
"level": {
"type": "array",
"items": {
"enum": [
"State Level",
"National",
"International"
]
},
"description": "Event level"
},
"start_date": {
"type": "string",
"format": "date",
"description": "Start Date"
},
"duration": {
"type": "number",
"description": "Duration in Days"
}
}
}
SCHEMA;
return json_encode($schema, true);
}
The schema can be dynamically loaded from a related Model or API.
Eg. to load the JSON schema from an EventType
Model, first create an attribute on the Model and call from the Nova resource.
In the Laravel Model:
public function getJsonSchemaAttribute() {
return $this->event_type->json_schema;
}
The event_type
Model should have an HasMany
relationship with the model holding the JSON data.
In the Nova Resource:
protected function loadSchema($request)
{
// NovaJsonSchemaField does not like empty JSON, so use an empty placeholder
$schema = $request->findModelQuery()->first()->json_schema ?? array();
return $schema;
}
- For Postgresql, use store the JSON Schema in a
JSON
column to preserve field order, do not useJSONB
for the schema. The JSON data values can be stored inJSON
orJSONB
.