对 laravel 5 中两个以上表中的用户进行身份验证

2022-08-30 13:09:39

据我所知,它用于从表中对用户进行身份验证,但我想从表中对其他用户进行身份验证,并从表中对管理员进行身份验证。我知道插件已经存在。但是,我们是否可以创建自己的用于从多个表中对用户进行身份验证..?Auth::attemptusersmanagersadminslaravel-multiauthAuthServiceProvider


答案 1

首先在“喜欢”中创建“管理员可验证”Illuminate\Foundation\Auth

    <?php

namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

    class Admin extends Model implements
        AuthenticatableContract,
        AuthorizableContract,
        CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;
    }

然后通过扩展管理模型来创建管理模型:-Authenticatable

  <?php
namespace App;
use Illuminate\Foundation\Auth\Admin as Authenticatable;

class Admin extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

之后,您需要修改如下添加提供程序数组config/auth.php

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

和“添加防护阵列”。

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

现在从用户表进行身份验证

 if (Auth::guard('user')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('user')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

并从管理表进行身份验证

 if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('admin')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

答案 2

您可以设置多个身份验证防护,每个防护都有不同的提供程序。提供程序定义要使用的表或模型。

在设置中,按如下方式设置,并且还为每个提供程序设置相应的设置:config/auth.phpprovidersguards

'providers' => [
    'users'  => [
        'driver' => 'eloquent',
        'model'  => App\User::class,
    ],
    'managers'  => [
        'driver' => 'eloquent',
        'model'  => App\Manager::class,
    ],
    'admins'  => [
        'driver' => 'eloquent',
        'model'  => App\Admin::class,
    ]
]

然后,您可以像这样进行身份验证:

Auth::attempt($credentials) // use default guard for simple users
Auth::guard('manager')->attempt($credentials)
Auth::guard('admin')->attempt($credentials)

查看文档 请点击此处。.


推荐