我正在使用Laravel 5.1构建一个RESTful API。默认路由为api
。用户可以使用任意数量的参数创建url服务,比如.../api/p1/p2/.../pn
。
如何创建指向单个控制器的单个路由,以便在单个控制器中处理服务?
注意:首先,应用程序只需要通过比较url
和数据库中存储的服务来知道服务是否存在。至于服务本身,稍后可以将其查询到数据库中。
我读到我们可以在Laravel 4中使用*
,那么Laravel 5.1呢?
我试过:
Route::resource('/api/*', 'APIServiceController');
,但它不适用于无限参数
或者可以像这个一样做吗
Route::group(['prefix' => 'api'], function () {
//what should I put in the closure, how can I redirect it to a single controller
});
将您的路线写如下:-
Route::group(['prefix' => 'api'], function () {
// this route will basically catch everything that starts with api/routeName
Route::get('routeName/{params?}', function($params= null){
return $params;
})->where('params', '(.*)');
});
重定向至控制器,
Route::group(['prefix' => 'api'], function () {
Route::get('routeName/{params?}', 'YourController@action')->where('params', '(.*)');
});
如果你想让routeName是动态的,那么只需将其写在花括号中,如下所示:-
Route::get('{routeName}/{params?}', 'YourController@action')->where('params', '(.*)');
希望它能帮助你:-)
你可以试试这个技巧
Route::get('{pageLink}/{otherParams?}', 'IndexController@get')->where('otherParams', '(.*)');
您应该把它放在routes.php文件的末尾,因为它就像一个"包罗万象"的路由。
class IndexController extends BaseController {
public function get($pageLink, $otherParams = null)
{
if($otherParams)
{
$otherParams = explode('/', $otherParams);
}
}
}