Laravel 4: redirect a send request using a different controller method

I have a controller as shown below
MyController:

public function methodA() { return Input::get('n')*10; } public function methodB() { return Input::get('n')*20; } 

I want to call a method inside MyController according to the 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?

+6
source share
3 answers

What, in my opinion, would be a cleaner solution is to send your mail 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 own 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()); } }); 

A source

OR

 Route:post('/', function(){ $flag = Input::get('flag'); if($flag == 1) { App::make('MyController')->methodA(); } else { App::make('MyController')->methodB(); } }); 

A source

And just to mention - I have absolutely zero practical experience with Laravel, I just searched and found this.

+6
source

This is for Laravel 4.x. When using Laravel 5 you need to add a namespace ... Question about Laravel 4


The Route::controller() method is what you need.

Your route 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 will look like this:

 public function methodA() { return Input::get('n') * 10; } public function methodB() { return Input::get('n') * 20; } 
+3
source

According to your answer in the comments, you need 1 url and decide which method to use based on the value of $ _POST. That's what you need:

In your Routes.php file add a generic 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!

+3
source

Source: https://habr.com/ru/post/975153/


All Articles