how to set new guard for auth controller in larave

2019-01-20 06:05发布

I want to make multiple authentication in my laravel project.

I create new guard "admin" in my auth.php file but I don't know how to set new created guard in my authcontroller.

It always use "defaults" settings from my auth.php:

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

3条回答
不美不萌又怎样
2楼-- · 2019-01-20 06:17

1) If you wish to use newly created admin guard throughout the application, you can change the value in defaults of config file.


2) If it is only about AuthController that uses Laravel's in built Auth system, you can add this line in the AuthController.php and PasswordController.php :

protected $guard = 'admin';

Ref - Check Guard Customization here


3) If you wish to you a guard other than default one for any Auth related task, you can specify it manually like this :

// For route middleware
Route::get('profile', [
    'middleware' => 'auth:admin',
    'uses' => 'ProfileController@show'
]);

// For manually logging the user in
if (Auth::guard('admin')->attempt($credentials)) {
    // Authenticated...
}

// To login specific user using eloquent model
Auth::guard('admin')->login($user);

// For getting logged in user
Auth::guard('admin')->user();

// To check if user is logged in
if (Auth::guard('admin')->check()) {
    // Logged in
}

Ref - https://laravel.com/docs/5.2/authentication

查看更多
趁早两清
3楼-- · 2019-01-20 06:24

Laravel 5.4+ uses the following in any Auth Controller:

use Illuminate\Support\Facades\Auth;

protected function guard(){
   return Auth::guard('guard-name');
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-20 06:39

You have to also register the guard in the config\auth.php

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

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

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

admin is the guard name, provider is the TABLE-NAME

查看更多
登录 后发表回答