Reputation: 3370
Now that to get data I call method from controller, that returns data as JSON:
return response()->json([$data]);
Can I add to this response global data? And merge this $data
?
For example I have global $user
object that I want to give away in each HTTP response to avoid the following entry in each method:
return response()->json(["data" => $data, "user" => $user]);
Upvotes: 1
Views: 7851
Reputation: 35200
An alternative to @rnj's answer would be to use middleware.
https://laravel.com/docs/5.4/middleware#global-middleware
This would allow you to instead hook in to the request rather than use a helper function that you may decide you don't want/need later.
The handle
method for your middleware could look something like:
public function handle($request, Closure $next)
{
$response = $next($request);
$content = json_decode($response->content(), true);
//Check if the response is JSON
if (json_last_error() == JSON_ERROR_NONE) {
$response->setContent(array_merge(
$content,
[
//extra data goes here
]
));
}
return $response;
}
Hope this helps!
Upvotes: 14
Reputation: 373
Create your own PHP class or function to wrap Laravel's response with your own data. Eg:
function jsonResponse($data)
{
return response()->json([
'user' => $user,
'data' => $data,
]);
}
Then you can call:
return jsonResponse($data);
This is just a simple example of how to keep your program DRY. If you're creating an application you're expecting to grow and maintain, do something more like this.
Upvotes: 2