'Give multiple permissions to a role - Spatie
How can we assign multiple permissions to a single role at once?
$permission1 = Permission::create(['name' => 'Create Client']);
$permission2 = Permission::create(['name' => 'View Invoice']);
$permission3 = Permission::create(['name' => 'Add Product']);
$role = Role::findById(1);
$role->givePermissionTo($permission1);
In above, I'm only giving permission to the first one.
As this is also achived by, $role->syncPermissions($permissions); Im confused how $permission includes multiple permissions?
Any advice please?
Solution 1:[1]
You can pass multiple permissions in array to
givePermissionTo().If you want to detach previously assigned permissions to the role, use
syncPermissions()Or you can even use laravel's sync method as Role has
morphToManyrelation with Permissions. so$role->permissions()->sync($permissions);also work
Solution 2:[2]
hello my suggestion is to use
$role = Role::findById(1); $role->givePermissionTo(Permission::all());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sazanrjb |
| Solution 2 | James Mark Saphani |
