如果您尝试检查用户是否可以从控制器访问您定义的任何门,您可以从现有的Authorizable 特征中获取一个队列,并在您自己的特征中添加一些额外的功能。
<?php
namespace App\Traits\MyAuthorizable;
use Illuminate\Contracts\Auth\Access\Gate;
trait MyAuthorizable {
public function canAny(array $abilities, $arguments = []) {
return collect($abilities)->reduce(function($canAccess, $ability) use ($arguments) {
// if this user has access to any of the previously checked abilities, or the current ability, return true
return $canAccess || app(Gate::class)->forUser($this)->check($ability, $arguments);
}, false);
}
public function canAll(array $abilities, $arguments = []) {
return collect($abilities)->reduce(function($canAccess, $ability) use ($arguments) {
// if this user has access to _all_ of the previously checked abilities, _and_ the current ability, return true
return $canAccess && app(Gate::class)->forUser($this)->check($ability, $arguments);
}, true);
}
}
use App\ MyAuthorizable;
您可以在您的用户类定义中将此特征添加到您的用户类中。
这将为您的用户公开canAny
和canAll
方法,然后您可以从控制器访问它们。
<?php
public function get($request) {
$User = Auth::User();
if ($User->canAll(['manage_global', 'manage_users', 'create_users'])) {
// user can do all of the things
} elseif ($User->canAny(['manage_global', 'manage_users', 'create_users']) {
// user can only do _some_ of the things
} else {
// user can do _none_ of the things
}
}