I have a problem regarding the response JSON of my API. I used a resource, since I wanted to limit what data to send back to the client. It was properly giving my intended response before, but when I opened my project again, the response changed.
Here's are parts of my code:
api.php
Route::get('admin/adminuserdetails/{adminUser}', 'AdminsController@AdminUserDetails');
Sample URL: http://localhost:8000/api/admin/adminuserdetails/1
Controller
public function AdminUserDetails(AdminUsers $adminUser){
return response()->json(new AdminUserAccessDetails($adminUser), 200);
}
AdminUsers Model
class AdminUsers extends Model
{
//
protected $table = 'AdminUsers';
protected $primaryKey = 'AdminUserId';
protected $guarded = [];
}
AdminUserAccessDetails Resource
class AdminUserAccessDetails extends JsonResource
{
public function toArray($request)
{
//return parent::toArray($request);
return [
'adminUserId' => $this->AdminUserId,
'adminFirstName' => $this->AdminFirstName,
'adminLastName' => $this->AdminLastName,
'modulesAllowed' => $this->ModulesAllowed,
'actionsAllowed' => $this->ActionsAllowed
];
}
}
Sample response (before, my intended response)
{
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"modulesAllowed": "",
"actionsAllowed": ""
}
Sample response (now)
{
{
"resource": {
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"adminEmail": "[email protected]",
"adminPassword": "l6wfDtAaYAp6aM04TU++9A==",
"authToken": "68bbc9fc7eb08c9f6d96f6b63d30f056",
"fCMToken": null,
"profileImage": "https://www.gravatar.com/avatar/5d0d65256e8c2b15a8d00e8b208565f1?d=identicon&s=512",
"userTypeId": "0",
"status": "A",
"createDate": "2018-06-26 16:01:43.947",
"updateDate": "2018-06-26 16:01:44.143",
"modulesAllowed": "",
"actionsAllowed": ""
},
"with": [],
"additional": []
}
I didn't change anything, but when I tested it again (not only in this particular route), everything that uses any resource is now enclosed within that resource wrap, and I can't seem to find the reason why.
I tried implementing the same logic with another clean project, and it's working perfectly.
What's causing this and how do I get my intended response back?
Edit 1: I tried to change my return, I removed the "response()->json()" code so my controller would look like:
public function AdminUserDetails(AdminUsers $adminUser){
//return response()->json(new AdminUserAccessDetails($adminUser), 200);
return new AdminUserAccessDetails($adminUser);
}
The response of this edit is now a bit closer to my intended output:
{
"data": {
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"modulesAllowed": "",
"actionsAllowed": ""
}
}
However I still prefer using the response()->json() so that I can return a proper HTTP response code..