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

如何基于randomString而非ID实现Laravel资源路由动态URL?

实现Laravel资源路由通过randomString字段访问Editor数据

要把原本基于ID的/editor/{id}访问改成用randomString字段的/editor/{randomString},只需要修改以下几个地方:

1. 配置Editor模型的路由绑定字段

在Editor模型中添加getRouteKeyName方法,告诉Laravel在路由模型绑定阶段使用randomString字段查找对应数据:

// app/Models/Editor.php
class Editor extends Model
{
    // ... 其他已有模型代码

    public function getRouteKeyName()
    {
        return 'randomString';
    }
}

2. 更新Vue列表页的跳转链接

把列表页中跳转链接的editor.id替换为editor.randomString,生成符合要求的URL:

<template>
    <div v-for="editor in editors" :key="editor.id">
        <Link :href="`/editor/${editor.randomString}`">
            进入编辑器详情
        </Link>
    </div>
</template>

<script setup>
import { Link } from '@inertiajs/vue3'

defineProps({
    editors: Array,
})
</script>

3. 控制器与路由无需修改

你的控制器show方法和资源路由定义保持原样即可:

  • 路由模型绑定会自动使用我们在模型中指定的randomString字段查找Editor记录
  • 资源路由Route::resource('editor', EditorController::class);的show路由规则还是/editor/{editor},只是参数解析逻辑已自动适配

如果需要在详情页展示randomString字段,可以直接在Vue组件中输出:

<template>
    <p>详情页</p>
    <p>ID: {{ editor.id }}</p>
    <p>随机标识: {{ editor.randomString }}</p>
</template>
<script setup>
defineProps({
  editor: Object,
})
</script>

修改完成后,访问/editor/{randomString}就能正确加载对应Editor的数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:20:04