Returning an Eloquent model as JSON in Laravel 4

蓝咒 提交于 2019-12-18 13:54:15

问题


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();

回答1:


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

#1 Sends Content-Type:application/json to the browser

#2 Sends Content-Type:text/html

#1 is more correct but it depends on your Javascript, see: What is the correct 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;



回答2:


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

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

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:

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

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




回答3:


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

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




回答4:


this solved my problem in laravel 5.5:

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


来源:https://stackoverflow.com/questions/15602129/returning-an-eloquent-model-as-json-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!