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

Laravel 8.0手动实现管理员与普通用户角色认证及路由最佳实践

Hey there! I totally get where you're coming from—wanting to grasp the manual implementation before leaning on packages like Breeze is such a smart move. Let's walk through a clean, secure, and straightforward way to separate admins and regular users in Laravel 8, with full Blade template support.

手动实现Laravel 8.0管理员与普通用户角色分离最佳实践

1. First: Update the Users Database Table

We need to add a role identifier to the users table. Using an enum is a solid choice here because it restricts valid values and keeps things consistent.

  • Generate a migration file:
    php artisan make:migration add_role_to_users_table
    
  • Open the migration file and add the role column:
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->enum('role', ['user', 'admin'])->default('user');
        });
    }
    
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('role');
        });
    }
    
  • Run the migration to apply changes:
    php artisan migrate
    

2. Add Role Check Methods to the User Model

To keep code clean and maintainable, add helper methods to your app/Models/User.php file:

// Check if the user is an admin
public function isAdmin()
{
    return $this->role === 'admin';
}

// Check if the user is a regular user
public function isUser()
{
    return $this->role === 'user';
}

These methods make role checks way more readable than hardcoding string values everywhere.

3. Secure Routes with Admin Middleware

For routes that only admins should access, we'll create a custom middleware to enforce permissions.

  • Generate the middleware:
    php artisan make:middleware AdminMiddleware
    
  • Open app/Http/Middleware/AdminMiddleware.php and add the validation logic:
    public function handle(Request $request, Closure $next)
    {
        // Redirect or abort if the user isn't logged in or isn't an admin
        if (!auth()->check() || !auth()->user()->isAdmin()) {
            abort(403, 'You don\'t have permission to access this page.');
        }
    
        return $next($request);
    }
    
  • Register the middleware in app/Http/Kernel.php (add to the $routeMiddleware array):
    protected $routeMiddleware = [
        // ... existing middleware
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
    ];
    
  • Now apply it to your admin-only routes:
    // Regular user dashboard (authenticated users only)
    Route::get('/dashboard', [DashboardController::class, 'userDashboard'])->middleware('auth');
    
    // Admin dashboard (authenticated admins only)
    Route::get('/admin/dashboard', [DashboardController::class, 'adminDashboard'])->middleware(['auth', 'admin']);
    

4. Role-Based Content in Blade Templates

You can easily show/hide content based on the user's role using the model methods we created:

Example: Navigation Menu

<nav class="navbar">
    <ul>
        @auth
            @if(auth()->user()->isAdmin())
                <li><a href="/admin/dashboard">Admin Dashboard</a></li>
                <li><a href="/admin/users">Manage Users</a></li>
            @endif
            <li><a href="/dashboard">My Dashboard</a></li>
            <li>
                <a href="{{ route('logout') }}" 
                   onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                    Logout
                </a>
                <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                    @csrf
                </form>
            </li>
        @endauth
        @guest
            <li><a href="{{ route('login') }}">Login</a></li>
            <li><a href="{{ route('register') }}">Register</a></li>
        @endguest
    </ul>
</nav>

Example: Page-Specific Content

<div class="content">
    <h1>Welcome to Your Dashboard</h1>
    
    @if(auth()->user()->isAdmin())
        <div class="admin-alert">
            <p>You're logged in as an admin—you have full access to all site features.</p>
        </div>
    @endif

    <!-- Content visible to all authenticated users -->
    <p>Here's your recent activity:</p>
    <!-- ... activity feed ... -->
</div>

5. Critical Security Notes

  • Never rely solely on Blade checks for sensitive actions: Hiding content in the frontend is just visual—always use backend middleware/policies to protect routes and data operations.
  • Avoid hardcoding role strings: Using the isAdmin() method means if you ever need to adjust role values (e.g., add a "moderator" role), you only need to update the model method instead of hunting down every instance in your codebase.
  • Restrict admin accounts: Keep the number of admin accounts minimal, and enforce strong password requirements for them.
  • For granular permissions: If you need more complex access control (e.g., admins can edit users but moderators can only ban), look into Laravel's built-in Policies—they work great with this role system.

Quick Note on Laravel Breeze

Once you're comfortable with this manual flow, Breeze is just a time-saver—it generates the basic auth scaffolding (login, registration, password reset) for you. You can easily drop the role logic we covered into Breeze's generated code to get the best of both worlds: speed and control.

内容的提问来源于stack exchange,提问作者Lex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:55:32