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

2022-01-08 00:00:00 api json php laravel laravel-4

如何将 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;

相关文章