【问题标题】:Route to two methods of controller with one row in Laravel 4在 Laravel 4 中使用一行路由到控制器的两种方法
【发布时间】:2015-03-12 02:36:58
【问题描述】:
这样路由很简单:
Route::get('user/profile', 'PaymentsController@profile');
Route::get('user/delete', 'PaymentsController@delete');
我想用一行来做这个:
Route::get('user/{subsection}', 'PaymentsController@'.$subsection);
但我的语法似乎是错误的。是否可以用一排完成?如果可以的话,那就太好了。
【问题讨论】:
标签:
laravel
methods
laravel-4
controller
routes
【解决方案1】:
不,你不能这样做,但你可以做代理方法
Route::get('user/{subsection}', 'PaymentsController@profileDelete');
方法看起来像
public function profileDelete($subsection) {
return $this->$subsection();
}
public function profile(){}
public function delete(){}
另外,你可以绑定{subsection}
Route::bind('subsection', function ($subsection) {
if (!in_array($subsection, ['profile', 'delete'])) {
throw new Exception;
}
return $subsection;
});
【解决方案2】:
不完全是一行,但你可以这样做:
Route::get('user/{subsection}', function($subsection){
if(!method_exists('PaymentsController', $subsection)){
App::abort(404);
}
return App::make('PaymentsController')->callAction($subsection);
});
除了method_exists,您还可以使用路由条件来仅允许预定义的子部分集:
Route::get('user/{subsection}', function($subsection){
return App::make('PaymentsController')->callAction($subsection);
})->where('subsection', '(profile|delete)');