Ad

Recommended Laravel Route Structure For Model Relationships

I know this question might be entirely opinion based but here goes. I would like to know the recommended way to structure routes based on model relationships in Laravel. Take for example the following three models:

User
Post
Comment

With their relationship (at the most basic) as follows:

User hasMany Posts
Post hasMany Comments

In my rotes file, I wish to get a list of Posts by a specific User. I might be inclined to use any of the following:

Route::get('/users/{user_id}/posts')
Route::get('/posts/{user_id}')

And also for fetching comments of a particular post I can use any of the two:

Route::get('/posts/{post_id}/comments')
Route::get('/comments/{post_id}')

Which method would be termed most recommended. And why? Thank you all!

Ad

Answer

Your first alternatives looks good:

Route::get('/users/{userId}/posts')
Route::get('/posts/{postId}/comments')

If you want to implement "the inverse" endpoint, how about more explicitly describing the route parameters:

Route::get('/posts/by-user/{userId}')
Route::get('/comments/for-post/{postId}')
Ad
source: stackoverflow.com
Ad