我对我的API的响应JSON有问题。我使用了一种资源,因为我想限制要发送回客户端的数据。之前可以正确地给出预期的响应,但是当我再次打开项目时,响应发生了变化。
这是我的代码的一部分:
api.php
Route::get('admin/adminuserdetails/{adminUser}', 'AdminsController@AdminUserDetails');
示例网址: http://localhost:8000/api/admin/adminuserdetails/1
控制器
public function AdminUserDetails(AdminUsers $adminUser){
return response()->json(new AdminUserAccessDetails($adminUser), 200);
}
AdminUsers模型
class AdminUsers extends Model
{
//
protected $table = 'AdminUsers';
protected $primaryKey = 'AdminUserId';
protected $guarded = [];
}
AdminUserAccessDetails资源
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
];
}
}
示例响应(在我预期的响应之前)
{
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"modulesAllowed": "",
"actionsAllowed": ""
}
示例响应(现在)
{
{
"resource": {
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"adminEmail": "asdfsadf@fsafsa.com",
"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": []
}
我没有做任何更改,但是当我再次测试时(不仅在此特定路由中),所有使用任何资源的内容现在都包含在该资源包中,并且我似乎找不到原因。
我尝试在另一个干净的项目中实现相同的逻辑,并且运行良好。
是什么原因造成的?如何获得我想要的答复?
修改1: 我尝试更改退货,删除了“ response()-> json()”代码,因此控制器如下所示:
public function AdminUserDetails(AdminUsers $adminUser){
//return response()->json(new AdminUserAccessDetails($adminUser), 200);
return new AdminUserAccessDetails($adminUser);
}
此编辑的响应现在更接近我的预期输出:
{
"data": {
"adminUserId": 1,
"adminFirstName": "asdfasdf",
"adminLastName": "asdfsadf",
"modulesAllowed": "",
"actionsAllowed": ""
}
}
但是我仍然更喜欢使用response()-> json(),以便我可以返回正确的HTTP响应代码。
答案 0 :(得分:0)
我认为问题是您正在发送Laravel对象作为API响应。请记住,Laravel Core实例对象添加了一些属性/方法,可轻松在代码内部进行管理/使用。
我建议您创建一个新的Class或Associative数组来封装特定属性,然后再发送。
例如:
public function AdminUserDetails(AdminUsers $adminUser){
// Example with Object
$Object = new YourClass(); // you can define with yours wished properties
$Object->PropertyA = $adminUser->Property1;
$Object->PropertyB = $adminUser->Property2;
// ...
return response()->json($Object, 200);
// Example with Associative Array
$AssociateArray = array(
"PropertyA" => $adminUser->Property1,
"PropertyB" => $adminUser->Property2,
// ...
);
return response()->json($AssociateArray, 200);
}
我希望会有用。