Multiple Authentication in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

Laravel, a popular PHP web framework, provides built-in support for multiple authentication systems. This allows developers to create separate authentication systems for different types of users, such as admins and regular users.

 

Multiple Authentication in Laravel

Here's how to implement multiple authentication in Laravel:

 

Step 1 - Create the authentication guards: In Laravel, guards are used to authenticate users for each type of authentication. You can create a guard for each authentication system by adding a new entry to the guards array in config/auth.php. For example, you could create a guard called "admin" for the admin authentication system:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

 

Step 2 - Create the authentication providers: Providers are used to retrieve user information for authentication. You can create a provider for each authentication system by adding a new entry to the providers array in config/auth.php. For example, you could create a provider called "admins" for the admin authentication system:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

 

Step 3 - Implement authentication: Now you can use the guard and provider you created to authenticate users. You can specify the guard to use when logging in and out by adding the guard name as the second argument to the Auth::attempt and Auth::logout methods. For example, to log in an admin user:

if (Auth::guard('admin')->attempt($credentials)) {
    // Authentication passed...
    return redirect()->intended('dashboard');
}

 

Step 4 -  Protect routes: To protect routes based on the user type, you can use the middleware provided by Laravel. For example, to protect a route so that only authenticated admin users can access it:

Route::get('/dashboard', function () {
    // Only authenticated admin users may enter...
})->middleware('auth:admin');

 

By following these steps, you can implement multiple authentication systems in Laravel.

Comments 0

Leave a comment