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"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="vendor/autoload.php"
colors="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
>
>
<source>
<include>
<directory suffix=".php">src/</directory>
@ -16,8 +17,6 @@
</testsuites>
<php>
<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"/>
</php>
</phpunit>

View File

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

View File

@ -35,13 +35,14 @@ trait HasRoles
} elseif (is_numeric($role)) {
$role = config('roles.models.role', \Blax\Roles\Models\Role::class)::find($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 {
throw new \InvalidArgumentException('Role must be a string, numeric ID, or an instance of Role.');
}
return $role
? $this->roles()->where('id', $role->id)->exists()
? $this->roles()->wherePivot('role_id', $role->id)->exists()
: false;
}