How do I make the post single URL like myweb.com/post-name instead myweb.com/post-id ? its works fine with posts id, but not with post name.
here my current route.
Route::get('/{id}', [ApphttpControllersPostController::class, 'show']);
and here my controller.
public function show($id) { $post = post::find($id); return view('detail', ['post' => $post]); }
thank you.
Advertisement
Answer
That is because you are using the $id
as the identifier to resolve the post object:
myweb.com/25
Then:
public function show($id) // $id = 25 { $post = post::find($id); // find() search for the PK column, "id" by default return view('detail', ['post' => $post]); }
If you want to resolve the $post
by a different field, do this:
public function show($name) { $post = post::where('name', $name)->first(); return view('detail', ['post' => $post]); }
This should work for a route like this:
myweb.com/a-cool-post-name
As a side note, you could resolve the model automatically makin use of Route Model Binding.