Certainly! To implement multi-role authentication where both admins and regular users share the same /login route but see different dashboards, you can use Laravel’s built-in authentication with some customization.
1. Database Design
Make sure your users table has a role column (e.g., admin, user).
php artisan make:migration add_role_to_users_table --table=users
In the migration:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('role')->default('user');
});
}
2. Authentication Logic
After login, redirect users based on their role. In app/Http/Controllers/Auth/LoginController.php, override the authenticated method:
protected function authenticated(Request $request, $user)
{
if ($user->role === 'admin') {
return redirect('/admin/dashboard');
}
return redirect('/user/dashboard');
}
3. Route Protection
In your routes/web.php:
Route::middleware(['auth', 'role:admin'])->group(function () {
Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
});
Route::middleware(['auth', 'role:user'])->group(function () {
Route::get('/user/dashboard', [UserController::class, 'dashboard']);
});
You’ll need a role middleware. Create it with:
php artisan make:middleware RoleMiddleware
In app/Http/Middleware/RoleMiddleware.php:
public function handle($request, Closure $next, $role)
{
if (auth()->check() && auth()->user()->role == $role) {
return $next($request);
}
abort(403, 'Unauthorized');
}
Register it in app/Http/Kernel.php:
'role' => \App\Http\Middleware\RoleMiddleware::class,
4. Login Route
Both admins and users log in from /login as usual.
Summary
- Add a
roleto users. - Redirect after login based on role.
- Protect dashboards with role-based middleware.
Recommended Series on Laracasts:
Check out "Multi-Authentication in Laravel" for an in-depth walkthrough.
Let me know if you need code for a specific part!