Search code examples
laravellaravel-routing

Pass parameters to '.index' controller function using Laravel resourceful routing


I'm using resourceful routing and I need to pass a parameter to the index function of the controller.

public function index($id){
// do something with $id
}

If I try to create a form like (say $user->id = 3):

{{ Form::open(array('route' => array('scopes.index', $user->id))) }}
{{ Form::close() }}

I get in the html this link: http://alumni.app/scopes?3 which is not good because it doesn't follow the URI for that named route. So, how should I proceed?

Discussion: I'm trying to load a list of scopes depending on the current user. I made an independent scopes controller.


Solution

  • The index action of a resource controller / route doesn't take any parameters by design.

    For filtering I suggest you use query parameters.

    /scope?userId=1
    
    {{ Form::open(array('route' => array('scopes.index', array('userId' => $user->id)))) }}
    

    Another approach would be nested resources (scroll down a bit)

    If you nest the scope resource inside user you could get this kind of url:

    /user/1/scope