Search code examples
phplaravelpermissionsuuidroles

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


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


Solution

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