Home > other >  How to show id in Resource Routes url?
How to show id in Resource Routes url?

Time:05-14

Update:

This line of code in the frontend was the culprit:

<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">

I had to change it to:

<inertia-link v-if="options.edit" :href="'/admin/gallery/1/edit'">

to make it comply with the laravel resource format for edit, provided by @Babak.

Original Post:

How would I transform this route in web.php:

Route::get('/admin/gallery/edit/{id}', function ($id) {
    $data = Gallery::find($id);
    return inertia('backend/cms-gallery-edit', ['data' => $data]);
});

to a resource route with its resource controller function:

Route::resource('/admin/gallery', GalleryController::class);

GalleryController.php:

public function edit($id)
{
    $data = Gallery::find($id);
    // assign id to end of route
    return inertia('backend/cms-gallery-edit', ['data' => $data]);
}

Edit:

I've tried both approaches of @Babak's answer, which work for index and create routes but the edit route still throws a 404. It is the only route encompassing an id.

web.php:

Route::resource('/admin/gallery', GalleryController::class)->only('index', 'create', 'edit');

GalleryController.php:

public function edit($gallery)
{
    $data = Gallery::find($gallery);
    return inertia('backend/cms-gallery-edit', ['data' => $data]);
}

Inertia passes the id from the frontend via href:

<inertia-link v-if="options.edit" :href="'/admin/gallery/edit/1'">

Browser shows:

GET http://127.0.0.1:8000/admin/gallery/edit/1 404 (Not Found)

CodePudding user response:

There is a fixed structure for laravel resource route method, you can see full list here. For edit page, it will generate something like '/admin/gallery/{gallery}/edit'

You can write it like below:

In your web.php file:

Route::resource('/admin/gallery', GalleryController::class)->only('edit');

And in your controller, name of the resource must be the same as your function's parameter.

public function edit($gallery)
{
    $data = Gallery::find($gallery);
    // assign id to end of route
    return inertia('backend/cms-gallery-edit', ['data' => $data]);
}

Or, you can customize it using parameter method. Refer to here

Route::resource('/admin/gallery', GalleryController::class)->only('edit')->parameters([
    'gallery' => 'id'
]);

And your controller

public function edit($id)
{
    $data = Gallery::find($id);
    // assign id to end of route
    return inertia('backend/cms-gallery-edit', ['data' => $data]);
}
  • Related