Jorge
Jorge

Reputation: 1730

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.

Upvotes: 3

Views: 9565

Answers (2)

Keshab Pal
Keshab Pal

Reputation: 41

You could create a separate route instead:

Route::get('scopes/{id}', ['as' => 'scopes.index', 'uses' => 'ScopeController@index']);

And exclude it from your resource route:

Route::resource('scopes', 'ScopesController', ['except' => ['index']]);

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 153030

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

Upvotes: 4

Related Questions