[英]Laravel 4: Redirect a post request to different controller method
我有一個像下面的控制器,
myController的:
public function methodA() {
return Input::get('n')*10;
}
public function methodB() {
return Input::get('n')*20;
}
我想根據POST值調用MyController中的方法。
routes.php文件
Route::post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
//execute methodA and return the value
} else {
//execute methodB and return the value
}
});
我怎樣才能做到這一點 ?
我認為更清潔的解決方案是根據您的標志將您的發布請求發送到不同的URL,並為每個URL提供不同的路由,這些映射到您的控制器方法
Route::post('/flag', 'MyController@methodA');
Route::post('/', 'MyController@methodB);
要按照您的方式執行操作,您可以使用此代碼段
Route:post('/', function(){
$app = app();
$controller = $app->make('MyController');
$flag = Input::get('flag');
if($flag == 1) {
return $controller->callAction('methodA', $parameters = array());
} else {
return $controller->callAction('methodB', $parameters = array());
}
});
要么
Route:post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
App::make('MyController')->methodA();
} else {
App::make('MyController')->methodB();
}
});
而且需要注意的是 - 我對Laravel的實踐經驗絕對沒有,我只是搜索並發現了這一點。
這是為Laravel 4.x. 使用Laravel 5時,需要添加命名空間......問題是關於Laravel 4
Route::controller()
方法就是您所需要的。
您的路線文件應如下所示:
Route:post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
Route::controller('/', 'MyController@methodA');
} else {
Route::controller('/', 'MyController@methodB');
}
});
方法看起來像這樣:
public function methodA() {
return Input::get('n') * 10;
}
public function methodB() {
return Input::get('n') * 20;
}
根據您在評論中的回答,您需要1個url並根據$ _POST值決定使用哪種方法。 這就是你需要的:
在Routes.php
文件中,添加一個通用方法
Route::post('/', 'MyController@landingMethod);
在MyController
文件中:
public function landingMethod() {
$flag = Input::get('flag');
return $flag == 1 ? $this->methodA() : $this->methodB();//just a cleaner way than doing `if...else` to my taste
}
public function methodA() { //can also be private/protected method if you're not calling it directly
return Input::get('n') * 10;
}
public function methodB() {//can also be private/protected method if you're not calling it directly
return Input::get('n') * 20;
}
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.