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?

avatar
Eduard Pertíñez i Juncosa

I am getting crazy with something that, i assume, should be easy and, at least doable:

I have this old table that stores a one dimentional array with php serialize. I want to edit it so I create an easy mutator in my model... protected function rmaTransContacto(): Attribute { return Attribute::make( get: fn (string $value) => json_encode(unserialize($value)), set: fn (string $value) => serialize(json_decode($value)), ); }

That should make the trick. Yet there is no way to acces the data this way. The form field values are empty and the json structure acts crazy. Don't know if there is any way with filament that I can access those serialized (but not jsoned) values. Nothing seems to work. Accessing some getters and setters with another name does not seem to help neither.

avatar

Awesome awesome awesome, you saved my life!

avatar

Thanks for your share