Laravel 5.6 新增用户角色及管理员注册角色分配需求问询
Alright, let's walk through exactly how to add those two new roles and let admins assign them during user registration, building on the Laravel role auth setup you already have in place. Here's a straightforward, step-by-step breakdown:
First up, you need to integrate your new roles into your user data structure. If you're using a simple role column on your users table (common for basic setups), update it to include your new roles with a migration:
// Run `php artisan make:migration update_role_column_in_users_table` first Schema::table('users', function (Blueprint $table) { // Replace 'editor' and 'viewer' with your actual new role names $table->enum('role', ['admin', 'editor', 'viewer', 'user'])->default('user')->change(); });
If you're using a separate roles table with a user_role pivot (for more complex permissions), just seed the new roles into the roles table:
// Run this in a seeder or via `php artisan tinker` Role::create(['name' => 'editor']); Role::create(['name' => 'viewer']);
Since only admins can register new users, add a role dropdown to your registration view that only admins can see:
<!-- In resources/views/auth/register.blade.php --> @if(auth()->user()->isAdmin()) <div class="mb-3"> <label for="role" class="form-label">Assign User Role</label> <select name="role" id="role" class="form-control"> <option value="user" selected>Regular User</option> <option value="editor">Editor</option> <option value="viewer">Viewer</option> </select> </div> @endif
(Note: I'm assuming you already have an isAdmin() method on your User model, like return $this->role === 'admin';)
Update your RegisterController to accept and save the role (defaulting to 'user' if the registrant isn't an admin):
// In app/Http/Controllers/Auth/RegisterController.php protected function validator(array $data) { $baseRules = [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]; // Only require role validation if admin is registering if(auth()->check() && auth()->user()->isAdmin()){ $baseRules['role'] = ['required', 'string', 'in:user,editor,viewer']; } return Validator::make($data, $baseRules); } protected function create(array $data) { // Use submitted role if admin, else default to user $assignedRole = auth()->check() && auth()->user()->isAdmin() ? $data['role'] : 'user'; return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'role' => $assignedRole, ]); }
Create a middleware to check if a user has the required role for a route:
- Generate the middleware:
php artisan make:middleware CheckRole - Update the middleware logic:
// In app/Http/Middleware/CheckRole.php public function handle(Request $request, Closure $next, ...$allowedRoles) { if (!auth()->check() || !in_array(auth()->user()->role, $allowedRoles)) { abort(403, 'You don\'t have permission to access this page.'); } return $next($request); } - Register the middleware in
app/Http/Kernel.phpunder$routeMiddleware:'role' => \App\Http\Middleware\CheckRole::class,
Apply the middleware to routes for your restricted views to control access:
// In routes/web.php // Only admins and editors can access the editor dashboard Route::get('/editor-dashboard', function () { return view('editor.dashboard'); })->middleware(['auth', 'role:admin,editor']); // Only admins, editors, and viewers can access viewer-specific content Route::get('/viewer-only-content', function () { return view('viewer.content'); })->middleware(['auth', 'role:admin,editor,viewer']);
If you need to conditionally display content within views, use role checks directly in Blade:
@if(auth()->user()->role === 'editor' || auth()->user()->isAdmin()) <a href="/editor-dashboard" class="nav-link">Editor Dashboard</a> @endif @if(in_array(auth()->user()->role, ['viewer', 'editor', 'admin'])) <div class="viewer-exclusive-content"> <!-- Content only visible to viewers and above --> </div> @endif
内容的提问来源于stack exchange,提问作者Rafael Andrews

