简体   繁体   中英

RESTful nested Laravel routes

I'm attempting to create an API URL structure with nested Laravel routes like the following:

/api/v1/tables -- list tables
/api/v1/tables/<id> -- show one table data
/api/v1/tables/<id>/update (post) -- update table data (inline editing of table, so edit screen not needed)
/api/v1/tables/<id>/settings -- get settings for that table
/api/v1/tables/<id>/settings/edit -- edit settings for that table
/api/v1/tables/<id>/settings/update (post) -- save settings for that table

I tried doing this with nested resources and two controllers. The TableController (tied to a Table model) would control the data in the table, and the TableSettings (tied to a TableSettings model) controller would control the settings (column names, order, visibility, etc). The idea being that you would call /api/v1/tables/<id> to get the data for the table and /api/v1/tables/<id>/settings to get the settings, then use this to build the display.

In my routes.php I have:

Route::group(array('prefix' => 'api/v1'), function()
{
  Route::resource('tables', 'TablesController',
                  array('only' => array('index', 'show', 'update')));
  Route::resource('tables.settings', 'TableSettingsController'.
                  array('only' => array('index', 'edit', 'update')));
});

I'd like to do something to this effect with to keep routes.php as clean as possible. The problem I'm running into is that when I try to hit either the settings edit or update URL ( /api/v1/tables/<id>/settings/<edit|update> ) it's actually looking for a URL in the form of /api/v1/tables/<id>/settings/<another_id>/edit . But I want it to use the table's ID rather than having a whole new settings ID in the URL.

Is there a way to use a nested resource controller in this way? Or should I use another method?

If you re-arrange the order of the resources - I think that will work:

Route::group(array('prefix' => 'api/v1'), function()
{
  Route::resource('tables.settings', 'TableSettingsController'.
                  array('only' => array('index', 'edit', 'update')));
  Route::resource('tables', 'TablesController',
                  array('only' => array('index', 'show', 'update')));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM