How to use multiple authentication passwords in laravel?

Member

by daisha , in category: PHP Frameworks , 9 months ago

How to use multiple authentication passwords in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 9 months ago

@daisha 

In Laravel, you can use multiple authentication passwords by configuring multiple guards in the config/auth.php file.


To define multiple guards, you'll need to specify the driver, provider, and password broker for each guard. Below is an example of multiple guards named users and admins:

  1. Open the config/auth.php file and locate the guards array.
  2. Add a new guard called admins as shown below:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
'guards' => [
    // ...
    'users' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

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


  1. Next, define the providers for the admins guard in the providers array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
'providers' => [
    // ...
    'users' => [
        'driver' => 'eloquent',
        'model' => AppModelsUser::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => AppModelsAdmin::class,
    ],
],


  1. You can also define multiple password reset providers by adding them to the passwords array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],

    'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],


  1. Now, you can utilize multiple authentication guards in your application. For example, to authenticate a User model, you can use:
1
2
3
if (Auth::guard('users')->attempt(['email' => $email, 'password' => $password])) {
    // User authentication successful
}


Similarly, you can use Auth::guard('admins') for the Admin model.


By following these steps, you can set up multiple authentication passwords in Laravel using guards, providers, and password brokers.