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

mdk999's avatar

Assign multiple roles by id

How do I assign multiple roles by id? I have an array of role id's that I need to assign to a user.

This doesn't seem to work ..

$user->roles()->attach(Role::whereIn('id', $data['roles']));

0 likes
3 replies
rawilk's avatar
rawilk
Best Answer
Level 47

It's not working because you do not have an array yet. You need to finish the query:

$user->roles()->attach(Role::whereIn('id', $data['roles'])->pluck('id')->toArray());

But if you already have the role ids, why wouldn't you just do this:

$user->roles->attach($data['roles']);
1 like
mdk999's avatar

Wanted to verify the input with the existing roles. Your suggestions worked - thanks

Please or to participate in this conversation.