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

Theraloss's avatar

Controller convention for "pivot" data

Hello, something I didn't really "solved" is the convention for Controllers for relationships data.

With a quick example, you have Users and Posts and you want to display all the posts of the given user. What will be your controller? UserController with a posts method? PostController with a indexForUser (or something like that)? UserPostController?

Any feedback or discussion is appreciated :)

0 likes
1 reply
martinbean's avatar
Level 80

@theraloss You’d use a nested resource controller called UserPostController, that has an index method which takes a user and lists the posts for that user:

class UserPostController extends Controller
{
    public function index(User $user)
    {
        $posts = $user->posts()->paginate();

        return view('user.post.index', compact('posts'));
    }
}
Route::get('users/{user}/posts', 'UserPostController@index');
1 like

Please or to participate in this conversation.