php 使用资源路由创建不基于id的动态URL

svmlkihl  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(78)

我有一个包含id和randomString列(也是唯一值)的数据库,我设置了一个资源路由,这样我就可以动态地获取数据库的URL,比如/editor/1等。
在资源控制器的标准使用中,show函数将从Editor模型中获取id,在这种情况下,是否有任何方法可以绕过这个问题,以便我可以访问数据库中的信息,如下所示:/editor/{randomString}?

public function show(Editor $editor)
    {
        return inertia(
            'Editor/Show',
            [
                'editor' => $editor
            ]
        );
    }
<template>
    <div v-for="editor in editors" :key="editor.id">
        <Link :href="`/editor/${editor.id}`">
Go to id
        </Link>
    </div>
</template>

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

defineProps({
    editors: Array,
})
</script>
<template>
<p>show</p>{{ editor.id }}
</template>
<script setup>

defineProps({
 editor: Object,
})
</script>
Route::resource('editor', EditorController::class);
<?php

namespace App\Http\Controllers;

use App\Models\Editor;
use Illuminate\Http\Request;
use Inertia\Inertia;

class EditorController extends Controller
{
   public function index()
   {
       return inertia(
           'Editor/Index',
           [
               'editors' => Editor::all()
           ]
       );
   }

   public function show(Editor $editor)
   {
       return inertia(
           'Editor/Show',
           [
               'editor' => $editor
           ]
       );
   }

}
cwtwac6a

cwtwac6a1#

如果你不想使用隐式模型,你只需要:

//you can use any variable name instead of $randomString
public function show($randomString)
{
     //your code
}

如果要更改列,可以使用getRouteKeyName()方法,例如:

class Editor extends Model
{
   /**
   * Get the route key for the model.
    */
    public function getRouteKeyName(): string
    {
       return 'slug';
    }
}
mctunoxg

mctunoxg2#

简单的解决方案是简单地创建一个路由,导入您希望返回到路由的模型,并传入列名{editor:configuration}

use App\Models\Configuration;
Route::get('/configuration/share/{editor:configuration}', function (Configuration $configuration) {
    return $configuration;
});

相关问题