You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FilamentPHP Builder无法将数据保存到JSON列问题求助

FilamentPHP Builder组件无法保存数据到JSON列的问题与解决方法

问题描述

使用FilamentPHP的Builder组件时,无法将数据保存到JSON列,但直接使用表单组件(不嵌套在Builder内)可以正常保存。

Post模型代码

protected $casts = [
    'audio' => 'json',
    'audio_title' => 'json',
];

protected $fillable = [
    'audio_title',
    'audio',
];

迁移代码

Schema::table('posts', function (Blueprint $table) {
    $table->json('audio_title')->nullable();
    $table->json('audio')->nullable();
});

Builder组件代码

\Filament\Forms\Components\Builder::make('Content')
    ->blocks([
        \Filament\Forms\Components\Builder\Block::make('Audio')
            ->schema([
                TextInput::make('audio_title'),
                FileUpload::make('audio')
                    ->directory('audio'),
            ]),
    ]),

可正常保存的代码(不使用Builder)

TextInput::make('audio_title'),
FileUpload::make('audio')
    ->directory('audio'),

解决方案

Filament不会自动将Builder组件的数据编码为JSON,需手动在资源页面的方法中处理数据的编码与解码。

创建记录时的处理

在Filament->resource->PostResource->Pages->CreatePost.php中添加mutateFormDataBeforeCreate方法:

protected function mutateFormDataBeforeCreate(array $data): array
{
    $data['content'] = json_encode($data['block']);
    
    return $data;
}

编辑记录时的处理

在Filament->resource->PostResource->Pages->EditPost.php中添加以下两个方法:

protected function mutateFormDataBeforeSave(array $data): array
{
    $data['content'] = json_encode($data['block']);
    return $data;
}

protected function mutateFormDataBeforeFill(array $data): array
{
    $data['block'] = json_decode($data['content'], true);
    return $data;
}

内容的提问来源于stack exchange,提问作者farhad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:52:26