Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel json response: response()->json() or $var->toJson()

I'm using Laravel (in fact Lumen) for my API. I have created a User model and I use this to retrieve all my users:

$users = User::all()

Now I want to return it as json but when I read the Laravel site I see two options. Which one is the best and why, and what is the difference?

return response()->json($users) (as described here)

return $users->toJson() (as described here)

like image 200
Jordy Avatar asked Dec 04 '16 23:12

Jordy


2 Answers

Use return response()->json($users);

only return response()->json() is truly http response with header content-type: application/json

return $user->toJson() just echo a string in json format. The content-type is text/html

like image 137
forehalo Avatar answered Oct 03 '22 01:10

forehalo


Actually laravel does that out of the box. just do this:

return $users;

and laravel takes care of that and returns your model collection in json.

like image 23
Hamid Parchami Avatar answered Oct 03 '22 02:10

Hamid Parchami