I've recently updated laravel-permissions bundle which caused me to have a MySQL constraint error while running my database seeder
Originally I had the following in my RolesTableSeeder:
DB::table('role_has_permissions')->delete();
DB::table('user_has_roles')->delete();
DB::table('user_has_permissions')->delete();
DB::table('roles')->delete();
DB::table('permissions')->delete();
$employee = Role::create(['name' => 'Employee']);
Permission::create(['name' => 'access employee portal']);
$employee->givePermissionTo('access employee portal');
Which worked without any issue. After updating laravel-permissions from 1.11.0 to 1.12.0 I started to get the following error:
[Illuminate\DatabaseQueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (xxx.role_has_permissions, CO
NSTRAINT role_has_permissions_permission_id_foreign FOREIGN KEY (permission_id) REFERENCES permissions (id) ON DELETE CASCADE) (SQL: insert into rol
e_has_permissions (permission_id, role_id) values (51, 84))
This is caused by the last line in my seeder:
$employee->givePermissionTo('access employee portal');
I solved it by doing the following:
DB::table('role_has_permissions')->delete();
DB::table('user_has_roles')->delete();
DB::table('user_has_permissions')->delete();
DB::table('roles')->delete();
DB::table('permissions')->delete();
$employee = Role::create(['name' => 'Employee']);
$employeePerm = Permission::create(['name' => 'access employee portal']);
$employee->givePermissionTo($employeePerm);
Hi @jonasva
I think this is because the permission cache still thinks the permissions you just deleted in your seeder still exist, including the 'access employee portal' permission (with its old id).
You can try clearing the permission cache with:
php artisan cache:forget spatie.permission.cache
This should solve your issue!
Good luck!
Most helpful comment
Hi @jonasva
I think this is because the permission cache still thinks the permissions you just deleted in your seeder still exist, including the
'access employee portal'permission (with its old id).You can try clearing the permission cache with:
This should solve your issue!
Good luck!