简体   繁体   中英

Laravel Multiple Auth::attempt

I have two models in my laravel v5.4 project, user and admin.

In config/auth.php i added admin to guards and providers as below :

'guards' => [

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

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

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


'providers' => [

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

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

Now in AdminController class i want to use Auth::attempt function but by default it uses the users table. I can change defaults in config/auth.php as below and it works but in this case i can not use Auth::attempt for users.

'defaults' => [
    'guard' => 'admin',
    'passwords' => 'users',
],

I want to set user as default but use Auth::attempt function for admin with a method like Auth::attempt('admin',[credentials]). How can i use Auth::attempt for Admin model?

You call the guard directly, like this:

Auth::guard('admin')->attempt($credentials);

Or with the helper:

auth()->guard('admin')->attempt($credentials);

Or, even shorter with the helper:

auth('admin')->attempt($credentials);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM