laravel5.1实现多用户认证
多用户认证是laravel5.2版本以上的新特性,在laravel5.1中是没有的。
要想实现在laravel5.1中进行多用户认证,则需要下载multiple auth 安装包
这里我们用 /Kbwebs/MultiAuth的安装包
Installation
首先,在composer.json
中引入kbwebs/multiauth
"require": {
"kbwebs/multiauth": "~1.0"
}
然后,compoer update
,等待下载完成。
Authentication
首先,打开config/app.php
,替换AuthServiceProvider
一行
Illuminate\Auth\AuthServiceProvider::class
-> Kbwebs\MultiAuth\AuthServiceProvider::class
然后,打开config/auth.php
,将下面的
'driver' => 'eloquent'
'model' => App\User::class,
'table' => 'users'
替换成
'multi-auth' => [
'admin' => [
'driver' => 'eloquent',
'model' => App\Http\Models\Admin::class,
'table' => 'users'
],
'user' => [
'driver' => 'eloquent',
'model' => App\Http\Models\User::class,
'table' => 'users'
]
],
现在的auth.php
中的内容
<?php
return [
'multi-auth' => [
'user' => [
'driver' => 'eloquent',
'model' => App\Http\Models\User::class,
'table' => 'users'
]
],
'password' => [
'email' => 'emails.auth.password',
'table' => 'password_resets',
'expire' => 60,
]
];
Password Reset
如果要实现密码重置,需要进行以下操作
首先,打开config/app.php
替换 Illuminate\Auth\Passwords\PasswordResetServiceProvider::class
为 Kbwebs\MultiAuth\PasswordResets\PasswordResetServiceProvider::class
在App\Http\Models\User.php
中
将use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
替换成use Kbwebs\MultiAuth\PasswordResets\CanResetPassword;
use Kbwebs\MultiAuth\PasswordResets\Contracts\CanResetPassword as CanResetPasswordContract;
重新生成password_resets
表php artisan kbwebs:multi-auth:create-resets-table
php artisan migrate
Usage
获取登录用户的信息Auth::user()->get()
;
或者Auth::user()->get()->role
;
Note:
凡是有Auth::的地方都需要修改为Auth::user()
否则会提示ErrorException in EloquentUserProvider.php line 112:
Undefined index: password
找到AuthenticatesUsers.php
将50行中的if (Auth::attempt($credentials, $request->has('remember'))) {
修改为if (Auth::user()->attempt($credentials, $request->has('remember'))) {
即可
转载请注明出处