Nieck
Nieck

Reputation: 1646

Laravel route to blogpost

I'm currently making a blog in laravel. I have a page that lists all the posts titles. When I click on a title it goes to the full post. So when I click on a post it goes from: localhost/posts to localhost/posts/{post_id}

The code I used to do that is:

@foreach($postsLists as $post)
<h1><a href="/posts/{{$post->id}}"> {{$post->title}}</a></h1> @endforeach

But the weird thing is when I place a comment on a specif blog post, and I go to another blog the url is broken.

It places /posts/{post_id} behind /posts. So I get /posts/posts/{post_id}. Which leads to nothing.

This is the code I use for my comments:

 public function store(Request $request, post $post) {
    $post->addComment(
        new Comment($request->all())
    );

    return back();
}

And this is the route to a blog post:

Route::get('posts/{post}', 'PostsController@showPost');

Does somebody know how to fix this problem? I tried many things but nothing works.

Thanks!

Upvotes: 1

Views: 778

Answers (2)

m0z4rt
m0z4rt

Reputation: 1225

 public function store(Request $request, $postId) {
    $post = Post::findOrFail($postId);
    $post->addComment(
        new Comment($request->all())
    );

    return back()->with('success', 'done!');
}

Upvotes: -1

Jeff
Jeff

Reputation: 25221

To ensure the proper URLs are generated for links, you can use Laravel's named routes. In routes.php:

Route::get('posts/{post}', 'PostsController@showPost')->name('posts.show');

In the template:

<h1>{{ link_to_route('posts.show', $post->title, [$post->id]) }}</h1>

You can use it in your controller also instead of back():

return redirect()->route('posts.show', [$post->id]);

Upvotes: 2

Related Questions