Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

akc4's avatar
Level 1

How to collapse this collection

I am using Laravel-permission on a ChatParticipants (all participants of a chat) model. Now every participants have specifc roles/permissions.

Here is my query participants on my Chat model:

public function participants()
    {
        return $this->hasMany(ChatParticipant::class, 'chat_id', 'id')->with([
            'details',
            'roles' => function ($q) {
                $q->select('name');
            },
            'permissions' => function ($q) {
                $q->select('name');
            }
        ]);
    }

my current output is this:

-Chats
	-Participants
		-Roles: [ 0 => {name: "role1"}, 1 => {name: "role2"} ]
		-Permissions: [ 0 => {name: "permission1"}, 1 => {name: "permission2"} ]

How can I collapse the Roles and Permissions where it would look like this:

-Chats
	-Participants
		-Roles: [ "role1", "role2" ]
		-Permissions: [ "permission1", "permission2" ]
0 likes
4 replies
akc4's avatar
Level 1

@michaloravec I can't use pluck on hasMany relation, surely there is a neat way of doing this without using a bunch of foreach loops?

MichalOravec's avatar

Don't use eager loading inside the definition of relationship as well.

akc4's avatar
Level 1

@michaloravec I end up with this.

$chats = Chat::with(['messages', 'participants'])->orderBy('updated_at', 'DESC')->get();

        foreach ($chats as $value) {
            foreach ($value->participants as $val) {
                $val->permissions = $val->permissions()->pluck('name');
            }
        }

which is exactly what I wanted but doesn't look as beautiful as I was expecting.

Please or to participate in this conversation.