我在我的路由上使用中间件,如下所示
Route::get('posts', 'PostControlle@index')->middleware('ability:super_admin,canViewPost,false');
但是我得到一个InvalidArgumentException。
我认为问题在于供应商zizaco托付src托付性状EntrustUserTrait.php类的ability()方法。所以,我已经在User.php模型类中重写了这个方法。
如果我们从路由或控制器类中传入capability中间件的第三个参数。如:Route::get('posts', 'PostController@index')->middleware("ability:super_admin,access-posts,true");
但是如果我们使用Blade指令那么它将是布尔值
@ability('super_admin','access-posts,access-comments',true)
所以,我们应该把它作为字符串传递给@能力刀片指令。如:
@ability('super_admin','access-posts,access-comments',['validate_all' => 'true'])
,我们需要重写能力方法。把下面的方法放到User.php文件
public function ability($roles, $permissions, $options = [])
{
// Convert string to array if that's what is passed in.
if (!is_array($roles)) {
$roles = explode(',', $roles);
}
if (!is_array($permissions)) {
$permissions = explode(',', $permissions);
}
// Set up default values and validate options.
$validateAll = (isset($options['validate_all']) && $options['validate_all'] === 'true') ? true : false;
if ($validateAll !== true && $validateAll !== false) {
throw new InvalidArgumentException();
}
if (!isset($options['return_type'])) {
$options['return_type'] = 'boolean';
} else {
if ($options['return_type'] != 'boolean' &&
$options['return_type'] != 'array' &&
$options['return_type'] != 'both') {
throw new InvalidArgumentException();
}
}
// Loop through roles and permissions and check each.
$checkedRoles = [];
$checkedPermissions = [];
foreach ($roles as $role) {
$checkedRoles[$role] = $this->hasRole($role);
}
foreach ($permissions as $permission) {
$checkedPermissions[$permission] = $this->can($permission);
}
// If validate all and there is a false in either
// Check that if validate all, then there should not be any false.
// Check that if not validate all, there must be at least one true.
if(($validateAll && (in_array(true,$checkedRoles) && in_array(true,$checkedPermissions))) ||
(!$validateAll && (in_array(true,$checkedRoles) || in_array(true,$checkedPermissions)))) {
$validateAll = true;
} else {
$validateAll = false;
}
// Return based on option
if ($options['return_type'] == 'boolean') {
return $validateAll;
} elseif ($options['return_type'] == 'array') {
return ['roles' => $checkedRoles, 'permissions' => $checkedPermissions];
} else {
return [$validateAll, ['roles' => $checkedRoles, 'permissions' => $checkedPermissions]];
}
}