Multi-Authentication in Laravel allows you to handle multiple user types or roles, each with its own authentication guard and provider. This is useful for applications that require separate access for admins, customers, or API consumers.
Laravel's authentication system is designed with flexibility in mind, and multi-authentication builds on this foundation by enabling diverse user management strategies.
Define multiple guards in config/auth.php
:
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
Apply middleware to routes for different user roles:
Route::middleware(['auth:admin'])->group(function () {
Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
});
Route::middleware(['auth:web'])->group(function () {
Route::get('/profile', [UserController::class, 'profile']);
});
This setup ensures that each user type is authenticated using its own guard, with tailored access to their respective routes and resources. It simplifies managing complex authentication scenarios and enhances application security.