Laravel在同一个控制器中执行多个功能

Is it possible to execute multiple functions in the same controller with one route. I thought it would be something like this but it doesn't work.

Route::get('getdata','controller@getData', 'controller@getData1', 'controller@getData2');

In the controller are these functions:

  • getData
  • getData1
  • getData2

Or is there a easier way?

In the controller

Add something like this.

class YourController extends Controller {
    //...

    protected function getAllData() {
        //Executes the seperate functions.
        $this->getData();
        $this->getData1();
        $this->getData2();
    }

    //...
}

This will execute the functions respectively.

Then from your route, you just call YourController@getAllData as the function of the controller.

It does not make sense if multiple controller actions are responsible for a single route. That's not how MVC works. You should have one and only one action for each route, and call every other function you need inside that action.

And remember, for best practices each method of the controllers must contain only the code to respond the request, not business logic, and if you have any other functions which needs to be called, put them in another other classes (layers).

class MyController extends Controller {

    public function myAction(MyService $myService) {
        $myService->getData();

        // not $this->getData()
    }
}