Calling a controller function from a function in Laravel

samalapsy

Oluwatimilehin Samuel Alapakristi

Posted on May 25, 2023

Calling a controller function from a function in Laravel

This article was originally Posted on Medium

While developing your application, there may be situations or use case where you need to call an existing controller’s function. Don’t worry, Laravel’s got you covered and there are different ways to achieve this result such as the following:-

Calling the desired controller from your function using dependency injection and passing all necessary parameters.
Creating a trait that can be utilised by controllers or functions.
Creating a Service class that can be called by the function or controller
Creating a custom helper function to perform the same task and then reference your helper where needed. etc
In this tutorial, we are focusing only on the first point (Calling the desired controller from your function using dependency injection and passing all necessary parameters).

Laravel has a powerful tool called Service container, which is used for managing class dependencies and performing dependency injection. It allows us inject the desired controller into the calling function or controller. This is an illustration of it’s usage below

app(ControllerName::class)->functionToBeReferenced($args);
Enter fullscreen mode Exit fullscreen mode

Now let’s apply this little knowledge.

In the example below, using the Request Facade style, we called a AnotherController and passed a request holding some set of data, headers and a POST request method. When this request gets to your controller, it is executed and the $result variable holds the response sent from AnotherController.

request facade implementation

For those who enjoy using the request helper style or need to maintain a codebase where the request helper function is being used, here’s how you can achieve the same request.

request helper implementation

What do you think about this approach? Also If you want to learn more about the Laravel’s Service Container tools, you can check Laravel’s documentation.

Thank you for you time and please don’t forget to hit the Follow button.

Buy me coffee

💖 💪 🙅 🚩
samalapsy
Oluwatimilehin Samuel Alapakristi

Posted on May 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related