我正在创建一个API资源:
public function toArray($request)
{
return [
'permissions' => Permission::all()
];
}
这是我的浏览器控制台中的结果Permission::all()
:
{
"data": {
"permissions": [
{
"id": 1,
"name": "index users",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 2,
"name": "create users",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 3,
"name": "view users",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 4,
"name": "update users",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 5,
"name": "delete users",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 21,
"name": "index settings",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 22,
"name": "view settings",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
},
{
"id": 23,
"name": "update settings",
"guard_name": "web",
"created_at": "2019-06-11 06:45:52",
"updated_at": "2019-06-11 06:45:52"
}
]
}
}
我想要一个这样的数组:
[
{ 'group': 'users', 'view': true, 'edit': false, 'create': true, 'delete':
true },
{ 'group': 'settings', 'view': true, 'edit': false, 'create': true, 'delete':
true },
]
这是我到目前为止得到的:
Permission::all()->mapToGroups(function
($item){
$exploded = explode(' ', $item->name);
$item->group = $exploded[1];
$item->verb = $exploded[0];
$item->can = [$item->verb => true];
return [$item['group'] => $item['can']];
})->map(function($group){
$permission = $group->collapse();
return $permission;
})
这是我的浏览器控制台中的结果:
{
"data": {
"permissions": {
"users": {
"index": true,
"create": true,
"view": true,
"update": true,
"delete": true
},
"settings": {
"index": true,
"view": true,
"update": true
}
}
}
}
这些是我的问题:
答案 0 :(得分:0)
toArrar()应该可以帮助您解决第一个问题