You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Spatie权限:如何获取超级管理员用户ID数组?

解决方法:使用Spatie权限扩展内置方法获取指定角色的用户ID数组

Spatie Laravel Permission扩展确实提供了内置方法实现这个需求,你之前尝试的User::role()写法本身是正确的,执行失败大概率是因为你的User模型没有引入对应的权限Trait。

第一步:确保User模型引入Trait

在App\Models\User模型中,必须引入HasRoles Trait才能使用角色相关的查询方法:

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;

class User extends Model
{
    use HasRoles;

    // 其他模型代码...
}

第二步:使用内置方法获取角色用户ID数组

引入Trait后,直接用role()方法就能快速查询拥有指定角色的用户ID:

// 获取所有拥有Super Admin角色的用户ID数组
$superAdminIds = User::role('Super Admin')->pluck('id')->toArray();

优化你的自定义函数

如果需要排除特定用户ID,不用先查询再循环unset,直接在Eloquent查询中添加whereNotIn即可,更高效简洁:

/**
 * @param string $role
 * @param array $exclude
 * @return array
 */
private static function getRoleUserIds(string $role = 'Super Admin', array $exclude = [129] ): array
{
    return User::role($role)
        ->whereNotIn('id', $exclude)
        ->pluck('id')
        ->toArray();
}

额外用法说明

role()方法还支持多种参数形式:

  • 传入角色ID:User::role(1)->pluck('id')->toArray();
  • 传入多个角色:User::role(['Super Admin', 'Editor'])->pluck('id')->toArray();
  • 传入角色实例:$role = Role::findByName('Super Admin'); User::role($role)->pluck('id')->toArray();

这种内置方法会自动处理model_has_roles表的关联查询,避免硬编码表名和model_type字段,代码更易维护且符合Laravel的Eloquent风格。

内容的提问来源于stack exchange,提问作者ThurstonLevi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:15:57