Ricardo Albear
Ricardo Albear

Reputation: 516

Eloquent, use pluck() to filter a deep collection

I need to return an array only with the permissions name column but cant make it work with a ->pluck()

class User
{
public function roleTeams()
    {
        return $this->hasMany(RoleTeam::class);
    }
}
class RoleTeams
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}
class Role
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }
}

This is the last code i try based on similar answers i found.

$permissions = $user->roleTeams()->with('roles.permissions')->pluck('roles.*.permissions.*.name')->all();

The expected result is

[
    'edit_user',
    'delete_user',
    ...
]

Upvotes: 0

Views: 1114

Answers (1)

Oleg Nurutdinov
Oleg Nurutdinov

Reputation: 633

So, I tried to simulate your situation. My code is:

$arr = [
    'id'    => 1,
    'name'  => 'User 1',
    'roles' => [
        [
            'id'          => 2,
            'name'        => 'Admin',
            'permissions' => [
                [
                    'id'   => 8,
                    'name' => 'edit_user',
                    'type' => 'editor',
                ],
                [
                    'id'   => 9,
                    'name' => 'delete_user',
                    'type' => 'deleter',
                ],
            ],
        ],
        [
            'id'          => 3,
            'name'        => 'Manager',
            'permissions' => [
                [
                    'id'   => 6,
                    'name' => 'do_smth1_with_user',
                    'type' => 'smth1',
                ],
                [
                    'id'   => 7,
                    'name' => 'do_smth2_with_user',
                    'type' => 'smth2',
                ],
            ],
        ],
    ],
];

$collection = collect([$arr]);

And have interested results. If use pluck() method like in your answer:

dd($collection->pluck('roles.*.permissions.*.name'));

The result would be like this:

Collection {#322 ▼
  #items: array:1 [▼
    0 => array:4 [▼
      0 => "edit_user"
      1 => "delete_user"
      2 => "do_smth1_with_user"
      3 => "do_smth2_with_user"
    ]
  ]
}

But if I use pluck() with collapse() method it looks like you want:

dd($collection->pluck('roles')->collapse()->pluck('permissions')->collapse()->pluck('name'));

And result is:

Collection {#322 ▼
  #items: array:4 [▼
    0 => "edit_user"
    1 => "delete_user"
    2 => "do_smth1_with_user"
    3 => "do_smth2_with_user"
  ]
}

To be honest, I don't know why it works like it works, but try to use it with collapse() method and let me know if it helps your or not. Hope my answer helps you to slove your problem.

Upvotes: 3

Related Questions