I have two virtualhost on a server. Each virtualhost has a laravel project installed (Project 1 and Project 2)
In Project 1 I have configured an API.
Can I call API methods from Project 2 without having to make an API call (guzzle or http request)? Directly accessing the controller of project 1?
thxs
I can’t find how to call a controller from another Laravel project
2
Answers
Actually, there’s no straightforward way to handle this because the code of each project lives in its own namespace, so you can’t directly access the other controller.
However, you can try communication between the two projects through IPC (Inter-Process Communication)
If you’re using services classes to handle business logic instead of writing all the code inside the controller, then you can proceed to create a custom artisan command that will invoke the adjacent method inside the service class, and in case you need to pass parameters then you can do this as well passing them one-by-one or serializing them into a JSON string that gets sent as a single parameter, and the receiving command will parse it and extract the data.
For example, let’s say that the first project has a command that extracts username from a string as follows:
Now, in order to call it from within the second project, you can use the
Process
facade that’s available under the namespaceIlluminateSupportFacadesProcess
, it returns an instance ofIlluminateProcessProcessResult
which you can call theoutput()
method to get the output of the process, here’s an example:Please notice that the
run()
method is synchronous (i.e. it blocks execution of the script until the forked process terminates)For asynchronous behavior, consult the
start()
method in Laravel documentation about Processes managementI hope I’ve made the answer clear and understandable
No, you cannot call API methods from Project 2 without making a call using Guzzle or HTTP requests.
If you try to call the methods directly from Project 2, without making an API call, you will run into various issues, such as security vulnerabilities.
It’s not recommended but, if you want such access, you can do it like this: