GroupBy和mapToGroups返回API资源中的对象

时间:2019-06-16 19:39:58

标签: laravel laravel-5

我正在创建一个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
            }
        }
    }
}

这些是我的问题:

  • 如您所见,结果是一个对象,而不是数组。如何将其更改为数组?
  • 如何删除键(“设置”,“用户”,...)并将其移动到单个数组中?就像我的示例一样?

1 个答案:

答案 0 :(得分:0)

toArrar()应该可以帮助您解决第一个问题