P粉2168079242023-09-06 19:18:57
The problem is that the spatie in allocateRole and syncRole works if the model exists
I mean Laravel model has "exists" attribute
vendor\spatie\laravel-permission\src\Traits\HasRoles.php contains some code from the allocateRole function
syncRoles is a wrapper for allocateRole
$model = $this->getModel(); if ($model->exists) { $this->roles()->sync($roles, false); $model->load('roles'); } else { $class = \get_class($model); $class::saved( function ($object) use ($roles, $model) { if ($model->getKey() != $object->getKey()) { return; } $model->roles()->sync($roles, false); $model->load('roles'); } ); }
Therefore DB::table('users')->insert($arrayWithUsersData);
Do not change the parameter "exists" in the model as it applies to the original data
So I had to switch to creating users one by one and saving them
$user = new User($userData); $user->save();
Now Spatie creates the proper relationship.