1

In case of building an api with Laravel do we need to return a json like this on each request :

$datas = User::find($id)->get();
return response()->json($datas);

Or just return the collection like this is enough ?

return $datas;

What is the cleanest way ? Thanks !

1
  • Collection is enough. Use response() if you want to return custom HTTP status code (e.g. 404). Commented Mar 10, 2021 at 17:16

2 Answers 2

3

The best way is to create resource:

php artisan make:resource UserResource

Within resource you define fields to return, so everything is over control. You can also pass additional meta data for pagination etc.

$datas = User::find($id)->get();
return UserResource::collection($datas);

Returned users is wrapped with data key:

{
  "data": [ users array here ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

1

Cleanest way of doing it to return the data with response:

return response()->json($data,200);

If you have multiple variables then you can do it as following:

$users = User::find($id)->get();
$admins = Admin::find($id)->get();
$data=['users'=> $users, 'admins'=>$admins];
return response()->json($data,200);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.