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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With