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"
}
@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
Most helpful comment
Why are you using
response()->json()?