在laravel 5 中对来自两个以上表的用户进行身份验证
据我所知,Auth::attempt
用于对 users
表中的用户进行身份验证,但我想对 managers
表中的其他用户进行身份验证和 admins
表中的 admin.我知道已经存在 laravel-multiauth
插件.但是我们可以创建自己的 AuthServiceProvider
来对来自多个表的用户进行身份验证吗?
As I know Auth::attempt
is used to authenticate users from users
table, but i want to authenticate another users from managers
table and admin from admins
table. I know there are laravel-multiauth
plugin already exist. But can we create our own AuthServiceProvider
for authenticating users from multiple tables..?
推荐答案
首先在 IlluminateFoundationAuth
中创建 Admin Authenticatable 就像
First create Admin Authenticatable in IlluminateFoundationAuth
like
<?php
namespace IlluminateFoundationAuth;
use IlluminateAuthAuthenticatable;
use IlluminateDatabaseEloquentModel;
use IlluminateAuthPasswordsCanResetPassword;
use IlluminateFoundationAuthAccessAuthorizable;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;
use IlluminateContractsAuthAccessAuthorizable as AuthorizableContract;
use IlluminateContractsAuthCanResetPassword as CanResetPasswordContract;
class Admin extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
然后通过扩展Authenticatable
管理模型来创建管理模型:-
Then create Admin Model by extending Authenticatable
Admin Model :-
<?php
namespace App;
use IlluminateFoundationAuthAdmin 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
添加提供者数组
After that you need to modify config/auth.php
like below
Add in providers array
'admins' => [
'driver' => 'eloquent',
'model' => AppAdmin::class,
],
并加入guards数组.
'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';
}
并从Admin表进行身份验证
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
$details = Auth::guard('admin')->user();
$user = $details['original'];
return $user;
} else {
return 'auth fail';
}
相关文章