Laravel 返回 json 或视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18356151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel return json or view
提问by David Wadge
I'm developing an API where if the user specifies the action with .json
as a suffix (e.g. admin/users.json
), they get the response in the return of json, otherwise they get a regular html View.
我正在开发一个 API,如果用户将操作指定.json
为后缀(例如admin/users.json
),他们会在 json 的返回中获得响应,否则他们会获得常规的 html 视图。
Some actions may not have a json response, in which case they would just return a html View.
某些操作可能没有 json 响应,在这种情况下,它们只会返回一个 html 视图。
Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.
有没有人有关于如何干净地实施的建议?我希望它可以通过路由来实现。
采纳答案by Atrakeur
I suggest you to create your application as an api.
我建议您将应用程序创建为 api。
Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).
Foreach 页面,需要两个控制器。每个控制器使用不同的路由(在您的情况下,一个路由以 .json 结尾,另一个没有)。
The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.
json 控制器以json 形式返回数据。“普通”控制器调用相应的 json 路由,反序列化 json,然后将结果数组传递给视图。
This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.
这样,您就有了一个可用的标准化 API(并得到维护,因为您自己的应用程序使用它),以及一个“普通”网站。
More information: Consuming my own Laravel API
更多信息:使用 我自己的 Laravel API
Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.
编辑:也许它可以通过过滤器实现,但我不确定,我现在没有时间自己尝试。
回答by Andy
In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().
在 Laravel 5.x 中,要实现两个功能,例如为 AJAX 或 JSON 请求发送数据以及为其他人返回视图模板,您只需检查 $request->ajax() 或 $request->isJson()。
public function controllerMethod(Request $request)
{
if ($request->ajax() || $request->isJson()) {
//Get data from your Model or whatever
return $data;
} else {
return view('myView.index');
}
}