如何为Response :: json()指定默认参数

zhe*_*aus 6 php laravel

有没有办法为Response :: json()指定默认参数?问题是,在我的情况下,Response :: json($ data)返回utf8,因为我需要指定额外的参数才能读取它:

$headers = ['Content-type'=> 'application/json; charset=utf-8'];
return Response::json(Course::all(), 200, $headers, JSON_UNESCAPED_UNICODE);
Run Code Online (Sandbox Code Playgroud)

这很无聊,看起来多余......

dar*_*aim 5

您可以在(基本)控制器中创建一个新方法来设置所有这些标头。

protected function jsonResponse($data) {
    $headers = ['Content-type'=> 'application/json; charset=utf-8'];
    return Response::json($data, 200, $headers, JSON_UNESCAPED_UNICODE);
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器路由中返回这样的响应:

return $this->jsonResponse(Course::all());
Run Code Online (Sandbox Code Playgroud)

或者您可以创建一个新的 UTF8JsonResponse 类,扩展 default Response,在构造函数中设置所有标头,然后返回该return new UTF8JsonResponse(Course::all())