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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15602129/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:34:19  来源:igfitidea点击:

Returning an Eloquent model as JSON in Laravel 4

phpjsonapilaravellaravel-4

提问by Nyxynyx

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.

你如何将 Eloquent 模型作为 JSON 返回给浏览器?下面两种方法有什么区别?两者似乎都有效。

#1:

#1:

return Response::json($user->toArray());

#2:

#2:

return $user->toJson();

回答by Brian Ortiz

The actual data sent is the same, however...

实际发送的数据是一样的,但是......

#1 Sends Content-Type:application/jsonto the browser

#1 发送Content-Type:application/json到浏览器

#2 Sends Content-Type:text/html

#2 发送 Content-Type:text/html

#1 is more correct but it depends on your Javascript, see: What is the correct JSON content type?

#1 更正确,但它取决于您的 Javascript,请参阅:什么是正确的 JSON 内容类型?

However, it is much simpler to just return the model. It is automagically returned as JSON and the Content-Type is set correctly:

但是,仅返回模型要简单得多。它自动以 JSON 形式返回,并且 Content-Type 设置正确:

return $model;

回答by juco

Response::json($someArray)is a generic way to return JSON data.

Response::json($someArray)是返回 JSON 数据的通用方法。

return $model->toJson()is specific to returning a model as JSON. This would be my preferred approach when working with an Eloquent model.

return $model->toJson()特定于将模型作为 JSON 返回。在使用 Eloquent 模型时,这将是我的首选方法。

回答by Micael Gustafsson

In #1 you first convert your Eloquent to an array, and then you convert it to JSON, which seems a bit redundant.

在 #1 中,您首先将 Eloquent 转换为数组,然后将其转换为 JSON,这似乎有点多余。

With that in mind, I'd go with #2 if you're returning the JSON to the caller.

考虑到这一点,如果您将 JSON 返回给调用者,我会选择 #2。

Also note that, in L4, whenever an Eloquent model is cast to a string it will be automatically converted to JSON. Hence, you can do like in this example from the documentation to return JSON data directly from your route:

另请注意,在 L4 中,每当将 Eloquent 模型转换为字符串时,它都会自动转换为 JSON。因此,您可以像文档中的这个示例那样直接从您的路由返回 JSON 数据:

Route::get('users', function()
{
    return User::all();
});

For more information, see http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

有关更多信息,请参阅http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

回答by Wellington Alves

this solved my problem in laravel 5.5:

这解决了我在 laravel 5.5 中的问题:

function allUsers()
{
    $users = \App\User::all();
    $usersJson = json_encode($users);
    return $usersJson;
}