我和spatie/laravel-permissions有个问题..。
我在AuthServiceProvider.php中使用AuthServiceProvider.php定义Superadmin (可以绕过所有权限而不将其注册到角色).
它与can('the-permission')助手完美地工作在一起。
但它不适用于Auth::user()->hasPermissionTo('the-permission').
。
。
下面是我的代码:
。
在AuthServiceProvider.php中
public function boot()
{
$this->registerPolicies();
Gate::before(function ($user, $ability) {
$superadmin_rolename = 'Superadmin';
$guard_name = 'web-admin';
return $user->hasRole($superadmin_rolename , $guard_name ) ? true : null;
});
}。
。
在刀片中:
@can('add products')
<button type="submit">Add Product</button>
@endcan
// this will work perfectly, the button will be shown。
。
主计长:
public function addProduct()
{
$admin = Auth::guard('web-admin')->user();
if($admin->hasPermissionTo('add products')) return true;
return false;
}
// this is not working (it return false)... i dont know why.... it should return true....所以,正如我上面向你们展示的那样:
我使用superadmin
$user->can()
Gate超级管理员应该授予所有access
can()和can()完美地工作,而不是与$user->hasPermissionTo()一起工作谢谢
发布于 2019-09-25 09:26:23
基于@Remul的评论,我发现只有can()或$user->can()才能与Gate::before完美地合作.
那么,如果我想使用另一种方法,如$user->hasAnyPermission或$user->hasAllPermissions?
。
这就是我要做的.我决定在Admin模型中创建一个自定义方法。
<?php
namespace Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class Admin extends Authenticatable
{
use HasRoles;
protected $guard_name = "web-admin";
protected $fillable = ['name', 'email', 'password'];
public function canAny(array $permissions)
{
foreach($permissions as $e){
if($this->can($e)) return true;
}
return false;
}
public function canAll(array $permissions)
{
foreach($permissions as $e){
if(!$this->can($e)) return false;
}
return true;
}
}https://stackoverflow.com/questions/58093970
复制相似问题