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]);
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.