Tricks

Storing form data to JSON columns

Jun 15, 2022
Maazin
Admin panel, Form builder

You can store data to json columns using "dot" notation. In the below example currency code, name and symbol will be stored in the currency column:

use Filament\Forms\Components\TextInput;
 
TextInput::make('currency.code'),
TextInput::make('currency.name'),
TextInput::make('currency.symbol'),

Don't forget to add json cast to the model property:

use Illuminate\Database\Eloquent\Model;
 
class FooBar extends Model
{
protected $casts = [
'currency' => 'json',
];
 
// ...
}

If you need to store all data from a layout component to a json column, you could also use the statePath method on the component to scope all data inside to a json column.

use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
 
Section::make('Currency')
->statePath('currency')
->schema([
TextInput::make('code'),
TextInput::make('name'),
TextInput::make('symbol'),
]),

No comments yet…