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'))) {

即可


转载请注明出处


大步点点
191 声望14 粉丝

There are only two things you need to be a great programmer: curiosity and kindness. Everything else you can learn over time. Everything.