How to Implement Multiple Authentication Guards in Laravel 11

Implementing multiple authentication guards in Laravel 11 allows you to authenticate users against different sources or models within the same application. For instance, you might have separate authentication mechanisms for regular users and administrators. Here’s how to implement multiple authentication guards in Laravel:

  1. Define Guards: Start by defining authentication guards in your config/auth.php configuration file. Laravel comes with a default guard named “web” for web-based user authentication. You can define additional guards for different user types. For example, let’s create guards for “users” and “admins”.
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'user' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],
  1. Define Providers: Next, define authentication providers for each guard in the same configuration file. Providers specify how users are retrieved from the database or any other source.
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],
  1. Define Middleware: Laravel uses middleware to authenticate incoming requests. Create middleware for each guard to protect routes that require authentication. You can use the auth:guard middleware and specify the guard name.
Route::group(['middleware' => 'auth:user'], function () {
    // Routes for regular users
});

Route::group(['middleware' => 'auth:admin'], function () {
    // Routes for administrators
});
  1. Authenticate Users: When logging in users, specify which guard to use. For example, to authenticate a regular user, use the Auth::guard('user')->attempt() method.
if (Auth::guard('user')->attempt($credentials)) {
    // Authentication successful for regular users
}

Similarly, use Auth::guard('admin')->attempt() for administrators.

  1. Accessing Authenticated User: To retrieve the authenticated user, use the Auth::guard('guard_name')->user() method, where “guard_name” is the name of your guard.
$user = Auth::guard('user')->user();

By following these steps, you can implement multiple authentication guards in Laravel 11, allowing you to manage different types of users with distinct authentication mechanisms within the same application.

Leave a Reply