在 Laravel 4 中将 Eloquent 模型返回为 JSON

Returning an Eloquent model as JSON in Laravel 4(在 Laravel 4 中将 Eloquent 模型返回为 JSON)
本文介绍了在 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,请参阅:什么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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)