Posted on Leave a comment

SaaS with laravel (2)-租户权限

我们下一步需要给租户相应权限。

安装权限包:

composer require spatie/laravel-permission
php artisan vendor:publish
//发布 Provider: Spatie\Permission\PermissionServiceProvider
//迁移文件 xxxx_xx_xx_xxxxxx_create_permission_tables.php   moved to database/migrations/tenant folder

config/permission.php:
'models' => [
    'permission' => App\Permission::class,
    'role' => App\Role::class,
],
php artisan make:model Permission
php artisan make:model Role

Permission.php 文件:

<?php

namespace App;

use Hyn\Tenancy\Traits\UsesTenantConnection;
use Spatie\Permission\Models\Permission as BasePermission;

class Permission extends BasePermission
{
    use UsesTenantConnection;
}

Role.php 文件:

<?php

namespace App;

use Hyn\Tenancy\Traits\UsesTenantConnection;
use Spatie\Permission\Models\Role as BaseRole;

class Role extends BaseRole
{
    use UsesTenantConnection;
}

我们需要达到: 同时创建多个数据库的对应权限表,

config/tenancy.php 修改:

...
'tenant-seed-class' => TenantDatabaseSeeder::class,
...

php artisan make:seeder TenantDatabaseSeeder

<?php

use App\Permission;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;

class TenantDatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->addRolesAndPermissions();
    }

    private function addRolesAndPermissions()
    {
        // create permissions for an admin
        $adminPermissions = collect(['create user', 'edit user', 'delete user'])->map(function ($name) {
            return Permission::create(['name' => $name]);
        });
        // add admin role
        $adminRole = Role::create(['name' => 'admin']);
        $adminRole->givePermissionTo($adminPermissions);

        // add a default user role
        Role::create(['name' => 'user']);
    }
}

记得数据迁移文件要放在saas包路径:

database/migrations/xxxx_xx_xx_xxxxxx_create_permission_tables.php file to database/migrations/tenant folder

(1)文中创建的租户,我们应该授予他 管理员角色,所以修改 CreateTenant.php

...
private function addAdmin($name, $email, $password)
{
    $admin = User::create(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
    $admin->guard_name = 'web';  //here
    $admin->assignRole('admin');  //here

    return $admin;
}
...

再次执行 php artisan tenant:create boston boston@example.com, 看看效果:

检查数据库有没有新增: model_has_permissionsmodel_has_rolesrole_has_permissions, and roles

Leave a Reply

Your email address will not be published. Required fields are marked *