deb0rian
deb0rian

Reputation: 976

Laravel 4 RESTful API - resource controller - deeper request hierarchy

I'm building my frontend part of the API system. Using default Resource Controller's by Laravel you can achieve this type of requests:

http://superapi.com/v1/soccer/10

Which will call the: /app/controllers/SoccerController.php @ show($id) method

I need at least one more level of depth, to be able to do it like this:

http://superapi.com/v1/soccer/player/10

So it will resolve to:

/app/controllers/SoccerController.php @ show() method having both, "player" and "10" arguments.

public function show($model)
{
    return Response::json(array('success' => true, 'message' => 'Test ' . $model));
}

Laravel passes only 1 parameter to method, and I cannot find anything about how to pass more.

I'm doing this basically because my 1 controller is responsible for talking to a few Models, not just one. Either SoccerPlayer or SoccerTeam or SoccerSchedule, it all should be nicely put under /v1/<controller>/<type>/<id>

Advices?

Thanks!

Upvotes: 1

Views: 518

Answers (2)

pajooh
pajooh

Reputation: 1942

you can use route prefixing

Route::group(array('prefix' => 'soccer'), function()
{

    Route::resource('player', 'PlayerController');

});

then, you can put all soccer relavant controllers in the same namespace (and same folder) like Soccer. in this case, change the above route to

Route::resource('player', 'Soccer\PlayerController');

Upvotes: 0

Damien Pirsy
Damien Pirsy

Reputation: 25435

You can have the best of both worlds anyway, by placing a custom route before the resource route:

Route::get('soccer', 'SoccerController@show');
Route::resource('soccer', 'SoccerController', array('except' => array('show')));

Now the show() method will be escluded from the resource controller control (thus calling soccer/10 or soccer/player will lead to a NotFoundHttpException), and placed into your custom route. You'll need to edit the show() method to accept the second parameter though:

public function show($type, $id)
{

}

Upvotes: 1

Related Questions