skip to Main Content

I have a database which contains id and randomString columns (also unique value), i set up a resource route so i can dynamically get the url of the database like this /editor/1 etc.

In standart use of the resource controller the show function would get the id from the Editor model in this case, is there anyway to get around this so i can access the info from the database like this: /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 AppHttpControllers;

use AppModelsEditor;
use IlluminateHttpRequest;
use InertiaInertia;

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
           ]
       );
   }

}

2

Answers


  1. Chosen as BEST ANSWER

    Easy solution is to simply create a route, import the model you want to returned to the route, and pass in the column name {editor:configuration}

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

  2. If you don’t want to use implicit model, you just do:

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

    If you want to change the column, you can use getRouteKeyName() method, such as:

    class Editor extends Model
    {
       /**
       * Get the route key for the model.
        */
        public function getRouteKeyName(): string
        {
           return 'slug';
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search