I hasRole trait

This commit is contained in:
a6a2f5842 2025-06-18 19:02:51 +02:00
parent 93e952a271
commit 20162a4931
3 changed files with 27 additions and 23 deletions

View File

@ -1,23 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <phpunit
bootstrap="vendor/autoload.php" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
colors="true" bootstrap="vendor/autoload.php"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd" colors="true"
> xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
<source> >
<include> <source>
<directory suffix=".php">src/</directory> <include>
</include> <directory suffix=".php">src/</directory>
</source> </include>
<testsuites> </source>
<testsuite name="Permissions Test Suite"> <testsuites>
<directory>tests</directory> <testsuite name="Permissions Test Suite">
</testsuite> <directory>tests</directory>
</testsuites> </testsuite>
<php> </testsuites>
<env name="CACHE_DRIVER" value="array"/> <php>
<!-- APP_KEY required for Passport client --> <env name="CACHE_DRIVER" value="array"/>
<env name="APP_KEY" value="base64:W99w+5JYz8SVGf5sx17gmPR6uoNCtWiEVc+9qu8iGEg="/> <ini name="memory_limit" value="512M"/>
<ini name="memory_limit" value="512M"/> </php>
</php>
</phpunit> </phpunit>

View File

@ -14,11 +14,15 @@ class RoleMember extends Model
'member', 'member',
'context', 'context',
'expires_at', 'expires_at',
'created_at',
'updated_at',
]; ];
protected $casts = [ protected $casts = [
'context' => 'array', 'context' => 'array',
'expires_at' => 'datetime', 'expires_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
]; ];
public function __construct(array $attributes = []) public function __construct(array $attributes = [])

View File

@ -35,13 +35,14 @@ trait HasRoles
} elseif (is_numeric($role)) { } elseif (is_numeric($role)) {
$role = config('roles.models.role', \Blax\Roles\Models\Role::class)::find($role); $role = config('roles.models.role', \Blax\Roles\Models\Role::class)::find($role);
} elseif ($role instanceof Role) { } elseif ($role instanceof Role) {
return $this->roles()->where('id', $role->id)->exists(); // use pivot column to avoid ambiguous `id`
return $this->roles()->wherePivot('role_id', $role->id)->exists();
} else { } else {
throw new \InvalidArgumentException('Role must be a string, numeric ID, or an instance of Role.'); throw new \InvalidArgumentException('Role must be a string, numeric ID, or an instance of Role.');
} }
return $role return $role
? $this->roles()->where('id', $role->id)->exists() ? $this->roles()->wherePivot('role_id', $role->id)->exists()
: false; : false;
} }