php WIP:Spatie Laravel许可 - 延长给予和撤销使用给定防护名称的权限
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php WIP:Spatie Laravel许可 - 延长给予和撤销使用给定防护名称的权限相关的知识,希望对你有一定的参考价值。
<?php
namespace App\Traits;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
trait HasRolePermissionTrait {
use HasRoles;
/**
* Revoke the given permission.
*
* @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
* @param string
*
* @return $this
*/
public function revokePermissionToWithGuard($permission, $guard_name)
{
// if permission exist for the given guard, revoke
if (! $this->hasPermissionTo($permission, $guard_name)) {
throw GuardDoesNotMatch::create($guard_name, $this->getGuardNames());
}
$this->permissions()->detach($this->getStoredPermission($permission));
$this->forgetCachedPermissions();
return $this;
}
/**
* @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
*
* @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
*/
protected function getStoredPermissionByGuardName($permissions, $guard_name)
{
if (is_numeric($permissions)) {
return app(Permission::class)->findById($permissions, $guard_name);
}
if (is_string($permissions)) {
return app(Permission::class)->findByName($permissions, $guard_name);
}
if (is_array($permissions)) {
return app(Permission::class)
->whereIn('name', $permissions)
->whereIn('guard_name', $this->getGuardNames())
->get();
}
return $permissions;
}
/**
* Grant the given permission(s) to a role.
*
* @param array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
* @param string
*
* @return $this
*/
public function givePermissionToWithGuard($permissions, $guard_name)
{
$permissions = collect($permissions)
->flatten()
->map(function ($permission) {
return $this->getStoredPermission($permission);
})
->each(function ($permission) {
$this->ensureModelSharesGuard($permission);
})
->all();
$this->permissions()->saveMany($permissions);
$this->forgetCachedPermissions();
return $this;
}
}
以上是关于php WIP:Spatie Laravel许可 - 延长给予和撤销使用给定防护名称的权限的主要内容,如果未能解决你的问题,请参考以下文章
php Laravel上传Spatie Media Libary
php Laravel Spatie获得特定角色的用户
php Spatie Laravel Model状态范围具有状态
php Laravel Spatie更新用户和同步用户角色
php 具有Spatie Peermission包的Laravel Nova用户模型
PHP Laravel - 如何将 Spatie Async 用于并发函数