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'),
]),
avatar

This is one awesome trick. Together with reactive fields I can let appear different cards with different fields and store them in a json column.

avatar

Very good tutorial @Maazin

But I have a doubt. I used the repeater component to store (json) the ids of department members. Now I want to display the amount of members that are in the department, how can I make this loop? It's possible? And is there a way to also show the names of these people? I would have to get the IDs and query the members to get their names. Can you give me an example of how to do it?

avatar

I'm trying to achieve something similar. Did you find a way to do it?