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,9 +1,10 @@
<?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
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="vendor/autoload.php" bootstrap="vendor/autoload.php"
colors="true" colors="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
> >
<source> <source>
<include> <include>
<directory suffix=".php">src/</directory> <directory suffix=".php">src/</directory>
@ -16,8 +17,6 @@
</testsuites> </testsuites>
<php> <php>
<env name="CACHE_DRIVER" value="array"/> <env name="CACHE_DRIVER" value="array"/>
<!-- APP_KEY required for Passport client -->
<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;
} }