Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SparkyRih's avatar

Spatie permissions broken?

I'm going crazy, I'm trrying to use the Spatie Permission library, however, when I do this:

collect(Roles::all())->each(function ($role) {
    Role::create(['name' => $role, 'team_id' => 1]);
});
dump(role::findByName('administrator')); // results in:   There is no role named `administrator`.

And yes, the roles table does have the administrator role, and the guard (sanctum) does match as well.

0 likes
7 replies
SilenceBringer's avatar

@sparkyrih try to pass the guard explicitly

dump(Role::findByName('administrator', 'sanctum'));

for check you can grab it using DB facade

dump(DB::table('roles')->where('name', 'administrator')->where('guard', 'sanctum')->first());

maybe you have web guard use by default

By the way, I'm confused in difference between Roles and Role in your code

SparkyRih's avatar

This test does return the correct result. However, the Spatie library still doesn't (it uses the query Builder() under the hood).

In the code snippit above, Roles is an enum container roles (which olds 'administrator'). Role is the Spatie role model.

Also, my default guard is sanctumr.

SparkyRih's avatar

Took the wrong result, this is the actual query: "select * from "roles" where ("team_id" is null or "team_id" = ?) and "name" = ? and "guard_name" = ?"

This is the Spatie function:

protected static function findByParam(array $params = [])
    {
        $query = static::query();

        if (PermissionRegistrar::$teams) {
            $query->where(function ($q) use ($params) {
                $q->whereNull(PermissionRegistrar::$teamsKey)
                    ->orWhere(PermissionRegistrar::$teamsKey, $params[PermissionRegistrar::$teamsKey] ?? getPermissionsTeamId());
            });
            unset($params[PermissionRegistrar::$teamsKey]);
        }

        foreach ($params as $key => $value) {
            $query->where($key, $value);
        }
        
        return $query->first();
    }

The $params variable does actually contain the correct "namen" and "guard_name" (no "team_id")...

SparkyRih's avatar

Found it, I had to set the global team_id.

Please or to participate in this conversation.