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

Laravel Filament中为PostResource编辑页URL添加Slug

实现Filament中Post编辑路由用Slug替代ID的方案

要将Filament PostResource的编辑路由从ID改为Slug,只需完成以下3个关键步骤:

1. 修改Post模型的路由绑定字段

在Post模型中定义路由模型绑定使用的字段为slug,覆盖Laravel默认的id:

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

class Post extends Model
{
    // ... 其他模型代码

    // 指定路由模型绑定使用slug字段
    public function getRouteKeyName()
    {
        return 'slug';
    }

    // 可选:自动生成唯一slug(创建文章时自动处理)
    protected static function booted()
    {
        static::creating(function ($post) {
            // 从标题生成基础slug
            $baseSlug = Str::slug($post->title);
            $post->slug = $baseSlug;

            // 处理slug重复,添加数字后缀
            $count = 1;
            while (static::where('slug', $post->slug)->exists()) {
                $post->slug = "{$baseSlug}-{$count}";
                $count++;
            }
        });
    }
}

2. 确保Slug字段的唯一性

在posts表的迁移文件中,给slug字段添加唯一索引,避免路由冲突:

// database/migrations/xxxx_xx_xx_create_posts_table.php
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('slug')->unique(); // 添加唯一约束
        $table->text('description');
        $table->unsignedBigInteger('created_by');
        $table->string('status');
        $table->timestamps();
    });
}

3. 无需修改PostResource路由配置

你的getPages配置无需改动,因为Filament的{record}路由参数会自动使用模型定义的getRouteKeyName()返回的字段(即slug)生成URL:

// app/Filament/Resources/PostResource.php
public static function getPages(): array
{
    return [
        'index' => Pages\ListPosts::route('/'),
        'create' => Pages\CreatePost::route('/create'),
        'edit' => Pages\EditPost::route('/{record}/edit'), // 保持原配置即可
    ];
}

完成以上步骤后,创建新文章时会自动生成唯一slug,跳转的编辑页URL将变为http://127.0.0.1:8000/posts/你的文章slug/edit,且编辑页面能正常加载对应文章数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:07:17