Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an Eloquent model as JSON in Laravel 4

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(); 
like image 823
Nyxynyx Avatar asked Mar 24 '13 18:03

Nyxynyx


1 Answers

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; 
like image 160
Brian Ortiz Avatar answered Sep 28 '22 08:09

Brian Ortiz