You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Step 1: Add New Roles to Your Database

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']);
Step 2: Update the Registration Form for Admin-Only Role Selection

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';)

Step 3: Modify the Registration Controller to Handle Role Assignment

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,
    ]);
}
Step 4: Add Role-Based Access Middleware

Create a middleware to check if a user has the required role for a route:

  1. Generate the middleware:
    php artisan make:middleware CheckRole
    
  2. 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);
    }
    
  3. Register the middleware in app/Http/Kernel.php under $routeMiddleware:
    'role' => \App\Http\Middleware\CheckRole::class,
    
Step 5: Protect Your Specific Views with the Middleware

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']);
Step 6: (Optional) Show/Hide Content in Views Based on Role

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:13:44