Official documents
referenced article
- The model has all the permissions methods of operation
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
...
}
-
Each table relationship
which, model_id equivalent user_id, model_has_roles indicate the role owned by the user. -
Create an initial role (or roles you need) in seeder file
$user = $users->find(1);
$user->name = 'mushi';
$user->nickname = '虫子';
$user->save();
\Spatie\Permission\Models\Role::create([
'title' => '管理员',
'name' => 'admin',
'guard_name' => 'admin'
]);
- Add user roles operation (user table model to be introduced in the seeder
Spatie\Permission\Traits\HasRoles
, or other methods can not be used assignRole)
(related operating table model_has_roles)
// 为用户添加单个角色
$user->assignRole('admin');
// 数组形式的多个角色
$user->assignRole(['super_user', 'admin']);
// 同步角色(不存在添加,存在忽略)
auth()->user()->syncRoles(['admin']);