Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

php - 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();
question from:https://stackoverflow.com/questions/15602129/returning-an-eloquent-model-as-json-in-laravel-4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...