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 ?
In Laravel, sometimes is may be necessary to access a controller method from another controller. This is very easy to implement by simply including the controller with the required method in the controller that needs to access it.
Laravel offers an easy way to redirect a user to a specific page. By using the redirect() helper you can easily create a redirect like the following: return redirect('/home'); This will redirect the user to the /home page of your app.
By default laravel will redirect a user to the home page like so: protected $redirectTo = '/home'; To change that default behaviour, add the following code in App/Http/Controllers/Auth/LoginController. php . This will redirect users (after login) to where ever you want.
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());
}
});
Source
OR
Route:post('/', function(){
$flag = Input::get('flag');
if($flag == 1) {
App::make('MyController')->methodA();
} else {
App::make('MyController')->methodB();
}
});
Source
And just to note - I have absolutely zero practical experience with Laravel, I just searched and found this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With