1

I am using Laravel V:12 and Spatie Role/Permission V:6. for multiple roles (super_admin, sub_admin, user, sub_user). I created one seeder for creating an admin user and its role/permission.

At the time of the 4th step, I get an error. "Integrity constraint violation: 1048 Column 'team_id' cannot be null ---> insert into model_has_roles"

In config/permission.php

'teams' => true,
'team_foreign_key' => 'team_id',

Steps To Reproduce: In the seeder file write this code

//1. Create Permission
$permissions = ["role.view", "role.create", "role.edit", "role.delete"];
foreach ($permissions as $permission) {
  Permission::firstOrCreate([
    'name' => $permission,
    'guard_name' => 'web',
  ]);
}

// 2. Super Admin Role (Global)
$superAdminRole = Role::firstOrCreate([
  'name' => 'super-admin',
  'guard_name' => 'web'
]);
$superAdminRole->givePermissionTo(Permission::all());

// 3. Create Super Admin
$superAdmin = User::firstOrCreate(
  ['email' => '[email protected]'],
  [
   'user_type' => 1,
   'name' => 'Super Admin',
   'email_verified_at' => now(),
   'password' => Hash::make('Admin@12345'),
   'remember_token' => Str::random(10),
  ]
);

//4. Assign a role to the user
$superAdmin->assignRole($superAdminRole);

2 Answers 2

0

The reason for this issue is that you have a foreign key, a certain team_id in at least one of your tables. So you will need to check which of the four operations fail for you, make sure you identify what team that entity needs to belong to and make sure you set its team_id. So where you specify the array of fields you could do something like this:

    'team_id' => 123

and replace the value with the proper one.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you enabled 'teams' => true in config/permission.php, the package expects a team_id value whenever you assign a role/permission.

To assign team
$teamId = 1; // or fetch/create your default team

$superAdmin->assignRole($superAdminRole, $teamId);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.