https://dev.to/federicaferletti this tutorial was made with laravel 9 In this tutorial I will try to explain the One relation as best as possible
Controller/UserController.php php artisan make:controller UserController use App\Models\User; use App\Models\Role; public function updateRole(Request $request, $uuid) { $user = User::find($uuid); $role = Role::where('user_id', $uuid)->firstOrFail(); $validatedRoleUpdate = $request->validate([ 'role' => 'in:admin,user,student,educator', ]); $role->role = $validatedRoleUpdate['role']; $user->role()->save($role); return response()->json([ 'status' => true, 'message' => 'User Role Update Successfully', ], 200); } Well, now we do Seeder and Factory: php artisan make:factory UserFactory factories/UserFactory.php public function definition(){ return [ 'name' => fake()->name(), 'surname' => fake()->name(), 'email' => fake()->unique()->safeEmail(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password ]; } factories/RoleFactory.php public function definition() { return [ 'role' => 'user', ]; } seeders/UserSeeder.php php artisan make:seeder UserSeeder $user = User::factory() ->has(Role::factory()) ->create(); Last step let's test the updateRole method php artisan make:test UserTest --unit /* Command for run a specific test ./vendor/bin/phpunit --filter testUpdateRole tests/Unit/UserControllerTest.php */ public function testUpdateRole() { $id = User::all()->first()['id']; $response = $this->put("/api/users/{$id}/role", ['role' => 'student']); $response->assertStatus(200)->assertJson([ 'message' => 'User Role Update Successfully', ]); }