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

inmn's avatar
Level 2

Route Model Binding - nested routes via resource() function doable?

Lets say I have

  • Posts, Comments (belongsTo post); Rating belongsTo Comment)
  • Posts hasMany Comments; Comments hasMany Ratings.

If my goal is to reduce junk in Routes:

  • /post/
  • /post/id/comment/
  • /post/id/comment/id/rating/id

I can define

Route::resource('post', 'PostController');
Route::resource('comment', 'CommentController');
Route::resource('rating', 'RatingController');

Each will work, however, they do not force the relationship.

Ie, post/id loads post;

but /post/1/comment/ (all in index) loads every comment for all posts, not those belonging to Post #1

What is the best laravel esque way to handle this?

... or is " Route::resource() " not meant to do this type of specificity?

0 likes
4 replies
Snapey's avatar

Laravel used to document nested routes, but although the functionality is apparently still there, it has been removed from the docs

The thing is, although its cool to have like /post/4/comment/56/rating/3. post 4 and comment 56 are actually redundant since all you need to service the request is rating 3.

If the ids were relative (ie the 56th comment of post 4) then the full url would be relevant.

As it is, its not worth worrying about as I can't see it adds any value

inmn's avatar
Level 2

@snapey youre right other than the index function returning all of the comments, otherwise Create / Edit / etc are all just part of it.

I will search / ask the follow up question; but it revolves around nesting /comments/store

lcorbett2389's avatar

I know this is an old post but stumbled across it trying to solve the same issue. The link above is great for what I was looking for in @martinbean post, however for the Laravel version I'm currently using (6.0) the 'getForeignKey()' should be renamed to 'getForeignKeyName()' if anyone else finds this for later versions

Please or to participate in this conversation.