如何基于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
相关产品推荐
相关产品推荐

