I\'m writing a simple API, and building a simple web application on top of this API.
Because I want to \"consume my own API\" directly, I first Googled and found th
I was also just facing this issue and thanks to Jason's great answers I was able to make it work.
Just wanted to add that I found out that the Route also needs to be replaced. Otherwise Route::currentRouteName()
will return the dispatched route later in the script.
More details to this can be found on my blog post.
I also did some tests for the stacking issue and called internal API methods repeatedly from within each other with this approach. It worked out just fine! All requests and routes have been set correctly.
If you want to invoke an internal API and pass parameters via an array (instead of query string), you can do like this:
$request = Request::create("/api/cars", "GET", array(
"id" => $id,
"fields" => array("id","color")
));
$originalInput = Request::input();//backup original input
Request::replace($request->input());
$car = json_decode(Route::dispatch($request)->getContent());//invoke API
Request::replace($originalInput);//restore orginal input
Ref: Laravel : calling your own API
You are correct in that using Input
is actually referencing the current request and not your newly created request. Your input will be available on the request instance itself that you instantiate with Request::create()
.
If you were using (as you should be) Illuminate\Http\Request
to instantiate your request then you can use $request->input('key')
or $request->query('key')
to get parameters from the query string.
Now, the problem here is that you might not have your Illuminate\Http\Request
instance available to you in the route. A solution here (so that you can continue using the Input
facade) is to physically replace the input on the current request, then switch it back.
// Store the original input of the request and then replace the input with your request instances input.
$originalInput = Request::input();
Request::replace($request->input());
// Dispatch your request instance with the router.
$response = Route::dispatch($request);
// Replace the input again with the original request input.
Request::replace($originalInput);
This should work (in theory) and you should still be able to use your original request input before and after your internal API request is made.