Framework: Api resource missing data wrap when response is provide using response()->json(new UserResource($user))

Created on 19 Jun 2019  路  7Comments  路  Source: laravel/framework

  • Laravel Version: 5.8.23
  • PHP Version: 7.1.9
  • Database Driver & Version: Mysql 5.7

Description:

I am having issue when providing response using api resource.
The working response uses follows
return new UserResource($user); this works perfect as expected;
the response looks like below:
{
"data" :{
"id":"123",
"firstname":"dummy"
}
}
The below does not work:
return response()->json(new UserResource($user));
it gives following response:
{
"id":"123",
"firstname":"dummy"
}

Most helpful comment

Why are you using response()->json()?

All 7 comments

@bhaveshdaswani93

$data = new UserResource($user);
return response()->json(compact('data'));

@bhaveshdaswani93

$data = new UserResource($user);
return response()->json(compact('data'));

@qWici Thanks for the response, this is an alternate solution, but why in response()->json(new UserResource($resource) is not working same as return new UserResource($resource);

For side note what should i do if i have pagination for example i have PostResource and have 100 post
i want pagination so i can do like this return PostResource::collection(Post::paginate()); this will work but this will not work response()->json(PostResource::collection(Post::paginate()));

Why are you using response()->json()?

@bhaveshdaswani93 Yeah, @staudenmeir asked a right question. Your UserResourse by default extends from JsonResource and by default converted to array by toArray method

Why are you using response()->json()?

@staudenmeir
Thanks for response
I have created a trait for API response for my project
The final response I provide to API is like following
{"success":true/false,
"message":"",
"payload":UserResource/UserCollection(ApiResource)
}
When I provide response using this way I get only the user model
The additional functionality of ApiResource does not work.
How should I achieve this.
Or it is not possible to use ApiResource with response()->json();

Take a look at https://laravel.com/docs/eloquent-resources#adding-meta-data.

with() and additional() should be the features you are looking for.

OK I will try this approach
@staudenmeir
Can you suggest any way to use
JsonResouce and JsonResponse together or probably JsonResource within JsonResponse
While enjoying the benefits JsonResouce
Because it would be very convenient
For now I am closing this issue
Because I think this is not issue it could be a feature instead

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lzp819739483 picture lzp819739483  路  3Comments

felixsanz picture felixsanz  路  3Comments

jackmu95 picture jackmu95  路  3Comments

progmars picture progmars  路  3Comments

gabriellimo picture gabriellimo  路  3Comments