Issue
I have RESTful service that is available by endpoints.
For example, I request api/main
and get JSON data from server.
For response I use:
return response()->json(["categories" => $categories]);
How to control format of response passing parameter in URL?
As sample I need this: api/main?format=json|html
that it will work for each response
in controllers.
Solution
You can use for this Response macros. For example in AppServiceProvider
inside boot
method you can add:
\Response::macro('custom', function($view, $data) {
if (\Request::input('format') == 'json') {
return response()->json($data);
}
return view($view, $data);
});
and in your controller you can use now:
$data = [
'key' => 'value',
];
return response()->custom('your.view', $data);
If you run now for example GET /categories
you will get normal HTML page, but if you run GET /categories?format=json
you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.
Answered By - Marcin NabiaĆek
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.