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', ]); }
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners