How come you want to call a controller from a controller?
That sounds like you have some logic which needs to be extracted out.
A controller, in a sense is a entry point to your code. Once in, you shouldn't need to "re enter" the code...
I want to call my own API routes from controllers on a Laravel 5.2 app.
It works for the most part using the following:
$request = Request::create('api/v1/posts', 'POST')
$response = Route::dispatch($request)
Now on the API controller, I am using FormRequest to validate the request.
When validation fails, the default behavior of FormRequest is to redirect back with errors unless it's an ajax request, in which case it returns a JSON response.
Currently the $request is not getting interpreted as ajax and the FormRequest returns a RedirectResponse instead of a JsonResponse.
Is there away to specify that the $request I created should be interpreted as ajax or that it only accepts JSON responses? I haven't found a way to specify headers on the request.
I know I can override the response method on the FormRequest to always return JSON, but I would rather fix it on the request level.
Thanks.
Update: It seems adding the following works to change the request headers, however FormRequest is still not accepting it as ajax or wantsJson.
$request->headers->set('Accept', 'application/json');
The request received by the FormRequest has different Accept headers (and other headers too) than the ones I set which is why wantsJson is returning false. Where are the headers getting modified?
Update 2: Swapping the FormRequest on the API controller store method to Illuminate\Http\Request, we get the right Accept header on the request. So it seems like the issues comes from FormRequest.
On the API controller, this returns false (using FormRequest):
public function store(StorePostRequest $request)
{
dd($request->wantsJson());
}
This returns true (using Illuminate\Http\Request):
public function store(Request $request)
{
dd($request->wantsJson());
}
Please or to participate in this conversation.