I'm trying to use UUID for spatie, and followed the instruction from official document. Everything went well until I have to assignRole to user.
It return 0
Where it should have same value as role_id
these are my codes following the guide
config/permission.php
'models' => [
'permission' => \App\Models\Permission::class,
'role' => \App\Models\Role::class,
],
'column_names' => [
'role_pivot_key' => null, //default 'role_id',
'permission_pivot_key' => null, //default 'permission_id',
'model_morph_key' => 'model_ulid',
'team_foreign_key' => 'team_id',
],
user seeder
$user = User::create([
.
.
.
]);
// Set TeamId
setPermissionsTeamId(1);
$user->assignRole('superadmin');
both of my role and permission models
class Role extends SpatieRole
{
use HasFactory, HasUlids;
protected $primaryKey = 'ulid';
protected $fillable = [
'name',
'guard_name',
];
}
Found the issues here, I did some debugging on Spatie's code itself, and found out that when I tried inserting new user model, it has id of 0.
public function assignRole(...$roles)
{
$roles = $this->collectRoles($roles);
$model = $this->getModel();
$teamPivot = app(PermissionRegistrar::class)->teams && ! is_a($this, Permission::class) ?
[app(PermissionRegistrar::class)->teamsKey => getPermissionsTeamId()] : [];
if ($model->exists) {
$currentRoles = $this->roles->map(fn ($role) => $role->getKey())->toArray();
\DB::enableQueryLog(); // add this line
dump($this); // add this line
dump(array_diff($roles, $currentRoles), $teamPivot); // add this line
dump($roles, $currentRoles); // add this line
$this->roles()->attach(array_diff($roles, $currentRoles), $teamPivot);
dump(\DB::getQueryLog()); // add this line
$model->unsetRelation('roles');
}
.
.
.
}
Shown result from dump($this)
is this
#attributes: array:9 [
"id" => 0
"name" => "superadmin"
"email" => "superadmin@mail.com"
"email_verified_at" => "2024-06-06 13:47:23"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"active" => 1
"remember_token" => "U3feZKOcyA"
"updated_at" => "2024-06-06 13:47:23"
"created_at" => "2024-06-06 13:47:23"
]
So in the end I add public $incrementing = false;
on User Models and it solved the problems