Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david19's avatar

Change ID-->Name in URL

I can create posts via my controller. It works, but i like change id to {name}. I have a placeholder for Title, Body, Name.

Now i have http://localhost/posts/1,2...
Change to   http://localhost/posts/name
My route is: 
Route::resource('posts', 'PostsController');
My Controller@show:
public function show($id)
    {

        $post = Post::find($id);
        return view('posts.show')->with('post', $post);
    }

I migrate "name" in my db.

$table->string('name');

I try other answeres here in forum, but its not work.

0 likes
5 replies
shez1983's avatar

usually people will have slugs instead of name as they look more URL friendly..

you can do route model binding and then define the route binding key to be slug. all info is in documentation

david19's avatar

Thanks for your answere. The Problem is, i can not use

get

in my web.php. I call the controller with all ressources, index, create,show,edit,store...

Route::resource('posts', 'PostsController');

I can not find this in the documentation :(

MThomas's avatar

What you are looking for is route model binding : https://laravel.com/docs/5.8/routing. This’s will also pull in your model directly

Don’t forget to register the route key, in your case ‘name’ in the model.

Next you exclude the show route

‘’’ Route::resource('photos', 'PhotoController')->except([ 'show' ]); ‘’’

And create a get route for your show method, and change $id to whatever you used in your route to specify your model.

Sorry for bad markup, am on my iPhone.

david19's avatar

Sorry for my delay answere. This works:

Need a new controller, and a new route: Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Page;

class publicPageController extends Controller
{
  public function getSingle($url)
{

  $page = Page::where('url', $url)->first();
  return view('pages.public')->with('page', $page);
  }

}

Route:

Route::get('/{url}', 'publicPageController@getSingle')->name('publicPage.single');

Please or to participate in this conversation.