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

Nyx*_*nyx 37 php api json laravel laravel-4

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

#1:

return Response::json($user->toArray());
Run Code Online (Sandbox Code Playgroud)

#2:

return $user->toJson();
Run Code Online (Sandbox Code Playgroud)

Bri*_*tiz 34

发送的实际数据是相同的,但是......

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

#2发送 Content-Type:text/html

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

但是,返回模型要简单得多.它作为JSON自动返回,并且Content-Type设置正确:

return $model;
Run Code Online (Sandbox Code Playgroud)


小智 10

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

考虑到这一点,如果您将JSON返回给调用者,我将使用#2.

另请注意,在L4中,只要将Eloquent模型强制转换为字符串,它就会自动转换为JSON.因此,您可以在此示例中从文档中直接返回路径中的JSON数据:

Route::get('users', function()
{
    return User::all();
});
Run Code Online (Sandbox Code Playgroud)

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


juc*_*uco 9

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

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