Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel , how to call a function from another controller

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.

like image 618
edica Avatar asked Nov 08 '18 14:11

edica


People also ask

How can we call one controller method from another controller in laravel 8?

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.

How do you call a function in laravel?

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.


1 Answers

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]);
like image 62
Sasa Blagojevic Avatar answered Sep 24 '22 02:09

Sasa Blagojevic