Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 773
shavindip Avatar asked Jan 28 '26 13:01

shavindip


2 Answers

It seems you can pass an array to givePermissionTo, so you could just do the following:

$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, $permission2, $permission3]);
like image 93
Jerodev Avatar answered Jan 31 '26 18:01

Jerodev


  1. You can pass multiple permissions in array to givePermissionTo().

  2. If you want to detach previously assigned permissions to the role, use syncPermissions()

  3. Or you can even use laravel's sync method as Role has morphToMany relation with Permissions. so $role->permissions()->sync($permissions); also work

like image 43
sazanrjb Avatar answered Jan 31 '26 17:01

sazanrjb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!