Returning an Eloquent model as JSON in Laravel 4

前端 未结 4 794
既然无缘
既然无缘 2021-01-01 09:13

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:

         


        
4条回答
  •  暖寄归人
    2021-01-01 09:40

    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

提交回复
热议问题