如何更改 Laravel 中的响应?
How to change response in Laravel?
我有 RESTful 端点可用的服务。
例如,我请求 api/main
并从服务器获取 JSON 数据。
我使用的回复:
return response()->json(["categories" => $categories]);
如何控制URL中响应传递参数的格式?
作为示例,我需要这个:api/main?format=json|html
它适用于控制器中的每个 response
。
使用您的 format
查询参数示例,控制器代码将如下所示:
public function main(Request $request)
{
$data = [
'categories' => /* ... */
];
if ($request->input('format') === 'json') {
return response()->json(data);
}
return view('main', $data);
}
或者您可以简单地检查传入请求是否是通过 $request->input('format') === 'json'
和 $request->ajax()
的 AJAX 调用
一种选择是为此使用 Middleware
。下面的示例假设您将始终 returning view('...', [/* some data */])
即 view with data.
当“格式”应该是json
时,下面将return数据数组传递给视图而不是编译视图本身。然后,您只需将此中间件应用于可以具有 json
和 html
returned.
的路由
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->input('format') === 'json') {
$response->setContent(
$response->getOriginalContent()->getData()
);
}
return $response;
}
您可以为此使用 Response macros。例如在 AppServiceProvider
里面 boot
方法你可以添加:
\Response::macro('custom', function($view, $data) {
if (\Request::input('format') == 'json') {
return response()->json($data);
}
return view($view, $data);
});
现在您可以在您的控制器中使用:
$data = [
'key' => 'value',
];
return response()->custom('your.view', $data);
如果你现在 运行 例如 GET /categories
你会得到正常的 HTML 页面,但是如果你 运行 GET /categories?format=json
你会得到 Json 响应。但是,根据您的需要,您可能需要对其进行更多自定义以处理例如重定向。
我有 RESTful 端点可用的服务。
例如,我请求 api/main
并从服务器获取 JSON 数据。
我使用的回复:
return response()->json(["categories" => $categories]);
如何控制URL中响应传递参数的格式?
作为示例,我需要这个:api/main?format=json|html
它适用于控制器中的每个 response
。
使用您的 format
查询参数示例,控制器代码将如下所示:
public function main(Request $request)
{
$data = [
'categories' => /* ... */
];
if ($request->input('format') === 'json') {
return response()->json(data);
}
return view('main', $data);
}
或者您可以简单地检查传入请求是否是通过 $request->input('format') === 'json'
和 $request->ajax()
一种选择是为此使用 Middleware
。下面的示例假设您将始终 returning view('...', [/* some data */])
即 view with data.
当“格式”应该是json
时,下面将return数据数组传递给视图而不是编译视图本身。然后,您只需将此中间件应用于可以具有 json
和 html
returned.
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->input('format') === 'json') {
$response->setContent(
$response->getOriginalContent()->getData()
);
}
return $response;
}
您可以为此使用 Response macros。例如在 AppServiceProvider
里面 boot
方法你可以添加:
\Response::macro('custom', function($view, $data) {
if (\Request::input('format') == 'json') {
return response()->json($data);
}
return view($view, $data);
});
现在您可以在您的控制器中使用:
$data = [
'key' => 'value',
];
return response()->custom('your.view', $data);
如果你现在 运行 例如 GET /categories
你会得到正常的 HTML 页面,但是如果你 运行 GET /categories?format=json
你会得到 Json 响应。但是,根据您的需要,您可能需要对其进行更多自定义以处理例如重定向。