如何在 Laravel 中添加响应 HTTP 数据?
How to add in response HTTP data in Laravel?
现在为了获取数据我从控制器调用方法,returns 数据为 JSON:
return response()->json([$data]);
我可以向这个响应中添加全局数据吗?并合并这个 $data
?
例如,我想在每个 HTTP 响应中提供全局 $user
对象,以避免在每个方法中出现以下条目:
return response()->json(["data" => $data, "user" => $user]);
创建您自己的 PHP class 或函数以用您自己的数据包装 Laravel 的响应。例如:
function jsonResponse($data)
{
return response()->json([
'user' => $user,
'data' => $data,
]);
}
那么您可以拨打:
return jsonResponse($data);
这只是一个简单的例子,说明如何保持你的程序DRY. If you're creating an application you're expecting to grow and maintain, do something more like this。
@rnj 的答案的替代方法是使用中间件。
https://laravel.com/docs/5.4/middleware#global-middleware
这将允许您转而连接到请求,而不是使用您以后可能决定不使用的辅助函数 want/need。
您的中间件的 handle
方法可能类似于:
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;
}
希望对您有所帮助!
现在为了获取数据我从控制器调用方法,returns 数据为 JSON:
return response()->json([$data]);
我可以向这个响应中添加全局数据吗?并合并这个 $data
?
例如,我想在每个 HTTP 响应中提供全局 $user
对象,以避免在每个方法中出现以下条目:
return response()->json(["data" => $data, "user" => $user]);
创建您自己的 PHP class 或函数以用您自己的数据包装 Laravel 的响应。例如:
function jsonResponse($data)
{
return response()->json([
'user' => $user,
'data' => $data,
]);
}
那么您可以拨打:
return jsonResponse($data);
这只是一个简单的例子,说明如何保持你的程序DRY. If you're creating an application you're expecting to grow and maintain, do something more like this。
@rnj 的答案的替代方法是使用中间件。
https://laravel.com/docs/5.4/middleware#global-middleware
这将允许您转而连接到请求,而不是使用您以后可能决定不使用的辅助函数 want/need。
您的中间件的 handle
方法可能类似于:
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;
}
希望对您有所帮助!