SpoilCoconut's avatar

Display single post with post slug instead of post id.

By following the tutorial I've generated slug (actually unique slug for every posts)- https://laravelstream.com/generate-a-unique-slug-for-every-post-in-laravel My route is: Route::get('post/{id}', 'FrontController@singlePost')->name('post'); It's working perfectly with id.

But if I edit it like: Route::get('post/{slug}', 'FrontController@singlePost')->name('post'); and try to visit http://mylarapp.test/post/test-post I see Not Found 404 Not Found

I've put the line in my Post model: public function getRouteKeyName() { return 'slug'; } Not working yet. How I can solve the problem?

Controller: $data['recent_posts'] = Post::with('user', 'category')->select('id', 'title', 'slug', 'image', 'excerpt', 'category_id', 'user_id', 'created_at')->orderBy('created_at', 'desc')->paginate(9); return view('index', $data);

0 likes
3 replies
JeffreyWay's avatar

Your controller snippet is showing the page to fetch all recent posts. Can you instead share the action that shows a single post page?

SpoilCoconut's avatar

Hi Jeffrey, here is my code.

Controller for the single post: public function singlePost($slug){ $data['post'] = Post::findOrFail($slug); return view('post', $data); }

View for displaying the single post button: <a href="{{route('post', $recent_post->slug)}}">Read More</a>

Route: Route::get('post/{slug}', 'FrontController@singlePost')->name('post');

Hope that it'll help you to give me a solution.

Snapey's avatar
Snapey
Best Answer
Level 122

use route model binding

change the function

public function singlePost(Post $post)
{ 
    return view('post', compact('post')); 
}

and use post in the route

Route::get('post/{post}', 'FrontController@singlePost')->name('post');

and your button

<a href="{{route('post', $recent_post)}}">Read More</a>

provided $recent_post is an instance of Post model and your model binding is working ok

Please or to participate in this conversation.