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

chrisgrim's avatar

How to correctly add a review page to my url

Hi,

I have created posts like the tutorial on laracasts showed me. Then I created a review controller called postreviews where users can review the posts. Normally I call the postreviews on the individual post pages and display the content for that post.

What I wanted was to get the url www.site.com/post1/reviews so I created a route

Route::GET('/posts/{post}/reviews', 'PostReviewController@index');

This works great but I cant figure out how to only call the reviews for the specific post. Right now on my postreview index method I have

public function index()
    {
        $posts = Post::all();
        $postreviews = PostReview::latest();
        return view('ratings.index', compact('postreviews','posts'));
    }

I tried using $this-> but I am not sure that the postreview controller knows which post I am telling it to look for.

Am I setting this up correctly?

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

You have a nested controller, so all of the actions should receive the parent:

public function index(Post $post)
{
    $postreviews = $post->reviews()->latest()->get();

    return view('ratings.index', compact('postreviews', 'post'));
}

This assumes you have a reviews relation on the Post model.

chrisgrim's avatar

When I add the

public function index(Post $post)

it says sorry page cannot be found. In my post.php file I have

 public function reviews()
    {
      return $this->hasMany('App\PostReview');
    }

In my postreview.php file I have

public function posts(){
        return $this->hasOne('App\Post');
    }

Did I do something wrong with my relations?

tykus's avatar

It is not related to the page not found issue, but I would expect this should be a belongsTo, i.e. the foreign key post_id is in the post_reviews table.

How are you browsing to the page, using a Post id, for example/posts/123/reviews, or using a slug, i.e./posts/post-slug/reviews? The first way will use implicit Route Model Binding to find a Post instance with and id123`. In the second case, you would need to change the route key name on the Post model:

// Post.php
public function getRouteKeyName()
{
    return 'slug'; // where 'slug' is a column on the posts table.
}
chrisgrim's avatar

That fixed it!

I was using a slug. I will have to do some more research into getRouteKeyName. I did switch to slugs, but I don't completely understand what is going on under the hood.

Thanks so much!

Please or to participate in this conversation.