user role edit

This commit is contained in:
2026-05-11 12:28:38 +08:00
parent b0eef8fca1
commit 8c909adf62
7 changed files with 120 additions and 3 deletions

View File

@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use App\Http\Requests\UpdateUserRequest;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
@@ -28,8 +29,14 @@ class UserController extends Controller
*/
public function edit(User $user): View
{
$user->load('roles:id');
$roles = Role::query()
->orderBy('name')
->get(['id', 'name']);
return view('user.edit', [
'user' => $user,
'roles' => $roles,
]);
}
@@ -38,13 +45,19 @@ class UserController extends Controller
*/
public function update(UpdateUserRequest $request, User $user): RedirectResponse
{
$user->fill($request->validated());
$validated = $request->validated();
$roleIds = $validated['roles'] ?? [];
unset($validated['roles']);
$user->fill($validated);
if ($user->isDirty('email')) {
$user->email_verified_at = null;
}
$user->save();
$user->roles()->sync($roleIds);
return redirect()
->route('user.edit', $user)

View File

@@ -32,6 +32,8 @@ class UpdateUserRequest extends FormRequest
'max:255',
Rule::unique('users', 'email')->ignore($this->route('user')),
],
'roles' => ['nullable', 'array'],
'roles.*' => ['integer', 'exists:roles,id'],
];
}
}

View File

@@ -4,6 +4,16 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
#[Fillable(['name'])]
class Role extends Model {}
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
}

View File

@@ -7,6 +7,7 @@ use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
@@ -29,4 +30,12 @@ class User extends Authenticatable
'password' => 'hashed',
];
}
/**
* The roles that belong to the user.
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class);
}
}

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->primary(['role_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('role_user');
}
};

View File

@@ -31,6 +31,30 @@
<x-input-error class="mt-2" :messages="$errors->get('email')" />
</div>
<div>
<x-input-label :value="__('Roles')" />
<div class="mt-2 space-y-2 rounded-md border border-gray-200 p-4">
@forelse ($roles as $role)
<label class="flex items-center gap-2">
<input
type="checkbox"
name="roles[]"
value="{{ $role->id }}"
@checked(in_array($role->id, old('roles', $user->roles->pluck('id')->all()), true))
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
>
<span class="text-sm text-gray-700">{{ $role->name }}</span>
</label>
@empty
<p class="text-sm text-gray-500">{{ __('No roles available.') }}</p>
@endforelse
</div>
<x-input-error class="mt-2" :messages="$errors->get('roles')" />
<x-input-error class="mt-2" :messages="$errors->get('roles.*')" />
</div>
<div class="flex items-center gap-4">
<x-primary-button>{{ __('Save') }}</x-primary-button>

View File

@@ -1,5 +1,6 @@
<?php
use App\Models\Role;
use App\Models\User;
test('user edit page requires authentication', function () {
@@ -11,6 +12,8 @@ test('user edit page requires authentication', function () {
test('authenticated users can view the user edit page', function () {
$actingUser = User::factory()->create();
$user = User::factory()->create();
$role = Role::query()->create(['name' => 'Admin']);
$user->roles()->attach($role->id);
$response = $this
->actingAs($actingUser)
@@ -20,18 +23,24 @@ test('authenticated users can view the user edit page', function () {
->assertSuccessful()
->assertSee('Edit User')
->assertSee($user->name)
->assertSee($user->email);
->assertSee($user->email)
->assertSee('Roles')
->assertSee('Admin')
->assertSee('checked', false);
});
test('authenticated users can update a user', function () {
$actingUser = User::factory()->create();
$user = User::factory()->create();
$adminRole = Role::query()->create(['name' => 'Admin']);
$editorRole = Role::query()->create(['name' => 'Editor']);
$response = $this
->actingAs($actingUser)
->patch("/user/{$user->id}", [
'name' => 'Updated User',
'email' => 'updated@example.com',
'roles' => [$adminRole->id, $editorRole->id],
]);
$response
@@ -41,4 +50,25 @@ test('authenticated users can update a user', function () {
$this->assertSame('Updated User', $user->name);
$this->assertSame('updated@example.com', $user->email);
expect($user->roles()->pluck('roles.id')->all())
->toMatchArray([$adminRole->id, $editorRole->id]);
});
test('user roles can be cleared by submitting no roles', function () {
$actingUser = User::factory()->create();
$user = User::factory()->create();
$role = Role::query()->create(['name' => 'Admin']);
$user->roles()->attach($role->id);
$response = $this
->actingAs($actingUser)
->patch("/user/{$user->id}", [
'name' => $user->name,
'email' => $user->email,
]);
$response->assertRedirect("/user/{$user->id}/edit");
expect($user->refresh()->roles()->count())->toBe(0);
});