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

Laravel Filament 3:RichEditor按模型分目录存附件及编辑记录问题

解决方法

1. 模型层处理目录生成与删除

在Post模型中通过事件钩子,自动完成附件目录的创建和删除:

// app/Models/Post.php
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

protected static function booted()
{
    // 新建Post时生成唯一附件目录
    static::creating(function ($post) {
        $post->attachments_directory = 'posts/' . Str::uuid();
        Storage::makeDirectory($post->attachments_directory);
    });

    // 删除Post时同步删除整个附件目录
    static::deleting(function ($post) {
        if (Storage::exists($post->attachments_directory)) {
            Storage::deleteDirectory($post->attachments_directory);
        }
    });
}

2. 在PostResource中动态设置RichEditor存储路径

在PostResource的fields方法里,给RichEditor字段的path方法传入闭包。编辑场景下,闭包会接收到当前模型实例,直接调用其attachments_directory字段即可:

// app/Nova/PostResource.php
use Laravel\Nova\Fields\RichEditor;
use Illuminate\Http\Request;

public function fields(Request $request)
{
    return [
        // 其他字段...
        
        RichEditor::make('正文', 'main_text')
            ->path(function ($request, $model = null) {
                // 编辑模式:直接使用现有记录的附件目录
                if ($model) {
                    return $model->attachments_directory;
                }
                
                // 新建模式:生成临时目录(后续需同步到正式目录)
                $tempDir = 'posts/temp/' . Str::uuid();
                Storage::makeDirectory($tempDir);
                session()->put('post_temp_attachments_dir', $tempDir);
                return $tempDir;
            })
            ->disk('public'), // 根据你的文件存储磁盘配置调整
            
        // 其他字段...
    ];
}

3. 新建场景的文件迁移(可选)

如果新建时RichEditor先将图片上传到临时目录,需在模型创建后将文件迁移到正式目录,并更新正文中的图片路径:

// app/Models/Post.php
protected static function booted()
{
    // ... 保留之前的creating、deleting事件
    
    static::created(function ($post) {
        $tempDir = session()->get('post_temp_attachments_dir');
        if ($tempDir && Storage::exists($tempDir)) {
            // 移动临时目录到正式目录
            Storage::move($tempDir, $post->attachments_directory);
            // 更新正文中的图片路径
            $post->main_text = str_replace($tempDir, $post->attachments_directory, $post->main_text);
            $post->save();
            // 清理session中的临时目录标记
            session()->forget('post_temp_attachments_dir');
        }
    });
}

这样处理后,编辑现有Post时RichEditor会复用已有附件目录,不会重新生成;删除Post时附件目录也会被同步清理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:42:45