Assign Role to User, use UUID as primary key for all tables

Viewed 38

I am using UUID as primary key for all tables. When I am assigning the role to user return this

error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a c hild row: a foreign key constraint fails (leave_management.model_has_roles, CONSTRAINT model_has_roles_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE) (SQL: insert into model_has_roles (model_id , model_type, role_id) values (17a97eae-45c8-49b4-9985-453e2e2d50be, App\Models\User, 0))

User and Roles have keys but same error.

role table screenshot link.

user table screenshot link

2 Answers

as mentioned in SQLSTATE error role_id that you sent in query is not a valid role id and does not exists in your roles table (it evaluates as 0 if not exists)

So you should first make sure that the role already exists

For confirming that your role is valid first dump it somewhere and make sure that it's a valid role object It is possible that the role does not exist and the query result is null

Something like this question: https://github.com/spatie/laravel-permission/issues/1144

This is working like this

       'name' => 'Super-Admin',             
       'email' => 'superadmin@test.com',             
       'email_verified_at' => now(),             
       'password' => Hash::make('Superadmin123@'),         ]);         
   $role = \App\Models\Role::where('name', 'super-admin')->get();         
  $superAdmin->assignRole($role[0]);
Related