Home > Software design >  Assign Role to User, use UUID as primary key for all tables
Assign Role to User, use UUID as primary key for all tables

Time:08-20

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

CodePudding user response:

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 is 0)

so you should first create role and add its id as role_id field

CodePudding user response:

This is working like this

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