The M
The M

Reputation: 661

Laravel execute multiple functions in the same controller

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:

Or is there a easier way?

Upvotes: 0

Views: 4898

Answers (2)

Hamid Mohayeji
Hamid Mohayeji

Reputation: 4275

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()
    }
}

Upvotes: 0

Classified
Classified

Reputation: 560

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.

Upvotes: 4

Related Questions