如何在 Laravel 中为 auth 控制器设置新的保护

2021-12-18 00:00:00 php laravel laravel-5

我想在我的 Laravel 项目中进行多重身份验证.

I want to make multiple authentication in my laravel project.

我在 auth.php 文件中创建了新的守卫admin",但我不知道如何在我的 authcontroller 中设置新创建的守卫.

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

它总是使用我的 auth.php 中的默认"设置:

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

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

推荐答案

1) 如果您希望在整个应用程序中使用新创建的 admin 保护,您可以更改 defaults<中的值/strong> 的配置文件.

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

2) 如果只有 AuthController 使用 Laravel 内置的 Auth 系统,你可以在 AuthController.php 和 PasswordController.php 中添加这一行 :

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 - 检查 Guard 自定义 此处

3) 如果您希望为任何 Auth 相关任务设置一个非默认值的守卫,您可以像这样手动指定:

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
}

参考 - https://laravel.com/docs/5.2/authentication

相关文章