Laravel Laravel-Permission to use essays

Official documents
referenced article

  1. The model has all the permissions methods of operation
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
    ...
}
  1. Each table relationship
    Here Insert Picture Description
    which, model_id equivalent user_id, model_has_roles indicate the role owned by the user.

  2. 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'
	]);
  1. 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']);
Published 40 original articles · won praise 0 · Views 756

Guess you like

Origin blog.csdn.net/qj4865/article/details/104449346