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

kfirba's avatar
Level 50

Get route parameters from the request object

Hello.

Let presume I have a PostsController with an index() method which responds to 2 routes:

  1. /posts
  2. /users/{id}/posts

When it responds to the /posts route I want to return all posts paginated. When it responds to the /users/{id}/posts it should return all posts for that user paginated.

The difference is the index() method signature. If there is a user, I will need to accept an argument, but there may not be a user and then I don't need an argument in the method. Is there a way to get route parameters from the request object, so I can check and see if such a parameter exists do that, else do that.

0 likes
2 replies
pmall's avatar
pmall
Best Answer
Level 56
public function index ($user_id = null)
{
    // Retrieve from user if user_id not null, everything otherwise :)
}
1 like
phildawson's avatar

@kfirba I would do the above @pmall mentioned but if you went down the long-winded route()

Is there a way to get route parameters from the request object, so I can check and see if such a parameter exists do that, else do that.

public function index(Request $request)
{
    $user_id = $request->route()->parameter('id');

    // Retrieve from user if user_id not null, everything otherwise :)
}

4 likes

Please or to participate in this conversation.