Dar*_*ama 0 laravel laravel-5.4
现在,为了获取数据,我从控制器调用方法,将数据作为JSON返回:
return response()->json([$data]);
Run Code Online (Sandbox Code Playgroud)
我可以在此响应中添加全局数据吗?合并这个$data?
例如$user,我想在每个HTTP响应中放弃全局对象,以避免每个方法中的以下条目:
return response()->json(["data" => $data, "user" => $user]);
Run Code Online (Sandbox Code Playgroud)
@ rnj的答案的另一种选择是使用中间件.
https://laravel.com/docs/5.4/middleware#global-middleware
这将允许您改为挂钩请求而不是使用您可能决定以后不想要/不需要的帮助函数.
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;
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
2187 次 |
| 最近记录: |