spatie / laravel-permission

Associate users with roles and permissions
https://spatie.be/docs/laravel-permission
MIT License
12.13k stars 1.77k forks source link

Multiple guards for admin #1483

Closed M-P-programing closed 4 years ago

M-P-programing commented 4 years ago

Hi, I have a problem with multiple guards.

This is my seeder: `use Illuminate\Database\Seeder; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role;

class RolesAndPermissionsSeeder extends Seeder {

/**

If I remove $role2 works fine but if I use $role2 gives me this error after php artisan db:seed: `Seeding: RolesAndPermissionsSeeder

Spatie\Permission\Exceptions\GuardDoesNotMatch

The given role or permission should use guard web instead of web2.

at vendor/spatie/laravel-permission/src/Exceptions/GuardDoesNotMatch.php:12 8| class GuardDoesNotMatch extends InvalidArgumentException 9| { 10| public static function create(string $givenGuard, Collection $expectedGuards) 11| {

12| return new static("The given role or permission should use guard {$expectedGuards->implode(', ')} instead of {$givenGuard}."); 13| } 14| } 15|

  +4 vendor frames 

5 database/seeds/RolesAndPermissionsSeeder.php:46 Spatie\Permission\Models\Role::givePermissionTo(Object(Illuminate\Database\Eloquent\Collection))

  +8 vendor frames 

14 database/seeds/DatabaseSeeder.php:14 Illuminate\Database\Seeder::call("RolesAndPermissionsSeeder")`

I need that super-admin haves both guard web and guard web2 in order to have all the permissions. Am I missing something in the seeder in order to do that?

I have consulted https://docs.spatie.be/laravel-permission/v3/basic-usage/multiple-guards/#main but cant't find nothing related to this.

Thanks.

roydebangshu commented 4 years ago

You have to use

$role2->givePermissionTo(Permission::where('guard_name', 'web2')->get());

instead of

$role2->givePermissionTo(Permission::all());

because Permission::all() return permissions of all web guards.

M-P-programing commented 4 years ago

@roydebangshu thanks for your reply! And since is a super admin and I want him to have permissions for both web and web2 guards how could I pass that?

Could i do:

$role2 = Role::create(['guard_name' =>[ 'web','web2'],'name' => 'super-admin']); $role2->givePermissionTo(Permission::where(['guard_name' =>[ 'web','web2'],'));

because Without passing the guard names it just uses the default which is web...

drbyte commented 4 years ago

givePermissionTo() accepts an object, so if you get the Permission object for the specific guard you desire, it will skip doing a fallback lookup of the guard.

$permissionObject = Permission::where(['name'=>'foo', 'guard_name' => 'bar'])->first();
$role->givePermissionTo($permissionObject);