Laravel-permission: MySQL constraint error while assigning permissions to new role

Created on 23 Mar 2017  路  1Comment  路  Source: spatie/laravel-permission

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);

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:

php artisan cache:forget spatie.permission.cache

This should solve your issue!

Good luck!

>All comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

notflip picture notflip  路  3Comments

tripex picture tripex  路  3Comments

younus93 picture younus93  路  4Comments

neoreids picture neoreids  路  3Comments

enghelewa picture enghelewa  路  4Comments