Reputation: 1034
I have a controller like below,
MyController:
public function methodA() {
return Input::get('n')*10;
}
public function methodB() {
return Input::get('n')*20;
}
I want to call the a method inside MyController according to POST value.
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
}
});
How can i do this ?
Upvotes: 5
Views: 4339
Reputation: 5133
This is for Laravel 4.x. When using Laravel 5, you need to add Namespaces... The question is about Laravel 4
The Route::controller()
method is what you need.
Your routes files should look like this:
Route:post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
Route::controller('/', 'MyController@methodA');
} else {
Route::controller('/', 'MyController@methodB');
}
});
And the methods would look like this:
public function methodA() {
return Input::get('n') * 10;
}
public function methodB() {
return Input::get('n') * 20;
}
Upvotes: 3
Reputation: 16025
What I think would be a cleaner solution is to send your post request to different URLs depending on your flag and have different routes for each, that map to your controller methods
Route::post('/flag', 'MyController@methodA');
Route::post('/', 'MyController@methodB);
To do it your way, you can use this snippet
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());
}
});
OR
Route:post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
App::make('MyController')->methodA();
} else {
App::make('MyController')->methodB();
}
});
And just to note - I have absolutely zero practical experience with Laravel, I just searched and found this.
Upvotes: 6
Reputation: 6369
According to your answer in the comments, your need 1 url and deciding which method to use based on the $_POST value. This is what you need:
In your Routes.php
file, add a general method that
Route::post('/', 'MyController@landingMethod);
In your MyController
file:
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;
}
Hope this helps!
Upvotes: 3