问题描述
如何将 Eloquent 模型作为 JSON 返回给浏览器?下面两种方法有什么区别?两者似乎都有效.
How do you return an Eloquent model to the browser as JSON? What is the difference between the two methods below? Both seems to work.
#1:
return Response::json($user->toArray());
#2:
return $user->toJson();
推荐答案
实际发送的数据是一样的,但是...
The actual data sent is the same, however...
#1 发送 Content-Type:application/json
到浏览器
#1 Sends Content-Type:application/json
to the browser
#2 发送 Content-Type:text/html
#1 更正确,但它取决于您的 Javascript,请参阅:什么JSON 内容类型是否正确?
#1 is more correct but it depends on your Javascript, see: What is the correct JSON content type?
但是,仅返回模型要简单得多.它会自动返回为 JSON,并且 Content-Type 设置正确:
However, it is much simpler to just return the model. It is automagically returned as JSON and the Content-Type is set correctly:
return $model;
这篇关于在 Laravel 4 中将 Eloquent 模型返回为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!