Search code examples
collectionslaravel-8

How to get only nested data in Laravel collection


I wrote a database selection like this (Laravel 8):

$users = collect(User::with(['roles','roles.permissions'])->find(21));

The result is the following

=> Illuminate\Support\Collection {#2051
     all: [
       "id" => 21,
       "first_name" => "test",
       "name" => "test",
       "..." => "...",
       "roles" => [
         [
           "id" => 9,
           "name" => "Test",
           "permissions" => [
             [
               "id" => 13,
               "name" => "userReadList",
             ],
             [
               "id" => 11,
               "name" => "userUpdate",
             ],
           ],
         ],
         [
           "id" => 4,
           "name" => "responsible",
           "permissions" => [
             [
               "id" => 10,
               "name" => "userRead",
             ],
             [
               "id" => 9,
               "name" => "userCreate",
             ],
           ],
         ],
       ],
     ],
   }

Now: What I have to change in the query to get only an array, containing the permissions id as follow: [13,11,10,9]?

Or is my query principal wrong for getting the permissions id


Solution

  • I found the solution:

    $userPermissions = collect(User::with(['roles','roles.permissions'])->find(21));
    
    Arr::flatten(Arr::pluck($userPermissions['roles'] , 'permissions.*.id'));
    
    //[13,11,1,4,]
    

    But I think, the better way is the following

    $userPermissions = User::with(['roles','roles.permissions'])->find(21);
    
    $userPermissions->roles->pluck('permissions.*.id')->flatten()->toArray();
    
    //[13,11,1,4,]
    

    Also possible it the following approach

    $userPermissions = User::with(['roles','roles.permissions'])->where('id',21)->get();
    
    $userPermissions->pluck('roles.*.permissions.*.id')->flatten()->toArray();
    
    //[13,11,1,4,]