Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: Redirect a post request to different controller method

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 ?

like image 488
palatok Avatar asked Sep 11 '14 19:09

palatok


People also ask

Can we call function from another controller in Laravel?

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.

How do I redirect a route in Laravel?

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.

How do I redirect one page to another in Laravel?

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.


1 Answers

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);

EDIT:

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.

like image 129
php_nub_qq Avatar answered Sep 30 '22 06:09

php_nub_qq