在 Laravel 4 中将 Eloquent 模型作为 JSON 返回 [英] Returning an Eloquent model as JSON in Laravel 4

查看:34
本文介绍了在 Laravel 4 中将 Eloquent 模型作为 JSON 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 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,请参阅:What是正确的 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 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆