I have a controller with the "getUsers" function in a controller called "UserController" , and inside it I want to call a function of the "CarController" controller called "getCars", the two options I have are:
a) Make the second call as "static" , then I can call it without instantiating the class
b) Do not do that function of the static class and I call it in this way
$ car_id = 100;
$ userController = new UserController ();
$ userController-> getCars ($ car_id);
I do not know which is the best practice, or what pros or cons has one or another.
I'm using laravel. Thanxs.
Include the controller class which has the method you require in the controller that needs to access the method. Instantiate the controller class. Call the method.
You can call controller function on same controller using "$this" key variable. In this example, I will give you a very simple example of call a function from the same controller class. I will create getColorCode() private function for return color code from color name. that function i will call in index() method.
It is a bad practice to call a controller from another controller, this usually signals that you have badly designed your code and you should think of a different way to achieve what you want.
None the less, you can do it like this:
app()->call('App\Http\Controllers\CarController@getCars');
If your controller method has parameters you can pass them as the second argument:
app()->call('App\Http\Controllers\CarController@getCars', [$param1, $param2]);
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