我已经找到了处理嵌套资源控制器和传递多个约束的好信息,但似乎没有发现这个特定问题(可能是因为我认为这一切都错了!)。
如果我想在我的API中创建以下内容
我是否必须以这种方式为大多数人创建路线和控制器
Route::group(array('prefix' => 'myAwesomeCarApi'), function()
{
Route::resource('cars', 'CarsController');
Route::resource('cars/performance', 'CarsPerController');
Route::resource('cars/performance/parts', 'CarsPerPartsController');
Route::resource('cars.performance/parts', 'CarsPerPartsController');
Route::resource('parts', 'PartsController');
Route::resource('parts/performance', 'PartsPerController');
etc...
});
或者是否有一些技巧我缺少创建动态控制器,例如只有3(CarController,PartsController,PerformanceController)并处理代码中的不同路由?
答案 0 :(得分:5)
我认为您正在寻找的是嵌套资源控制器。这些允许您构建 / car / 1 / part / 1 等路线。此路线将映射到操作CarPartController@show
并传递两个参数:车辆ID和零件ID。
就汽车/零件的性能而言,我会说这有点像“show”方法(因为性能本身不是一个实体)所以会在你的控制器中创建另一种方法:
class CarPartController extends Controller {
public function show($carId, $partId)
{
// Show specified part for specified car
}
public function performance($carId, $partId)
{
// Show the performance for specified part on specified car
}
}
然后你的路线会是这样的:
Route::get('car/{car}/performance', 'CarController@performance');
Route::get('car/{car}/part/{part}/performance', 'CarPartController@performance');
Route::resource('car', 'CarController');
Route::resource('car/{car}/part', 'CarPartController');
根据Laravel文档,必须在资源控制器之前定义非资源方法。
您还可以进一步采用此方法并实现路由模型绑定,以便将Car
和Part
模型的实例注入控制器操作而不是ID:
Route::model('car', 'Car');
Route::model('part', 'Part');
示例控制器操作:
public function performance(Car $car, Part $part)
{
// Show performance for specified part on specified car
}
希望这有帮助。