laravel5.1 — 實現多使用者認證

Romolo發表於2019-02-16

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 一行

IlluminateAuthAuthServiceProvider::class -> KbwebsMultiAuthAuthServiceProvider::class

然後,開啟config/auth.php,將下面的

`driver`  => `eloquent`
`model`   => AppUser::class,
`table`   => `users`

替換成

`multi-auth` => [
    `admin` => [
        `driver` => `eloquent`,
        `model`  => AppHttpModelsAdmin::class,
        `table`  => `users`
    ],
    `user` => [
        `driver` => `eloquent`,
        `model`  => AppHttpModelsUser::class,
        `table`  => `users`
    ]
],

現在的auth.php中的內容

<?php

return [

    `multi-auth` => [
        `user` => [
            `driver` => `eloquent`,
            `model`  => AppHttpModelsUser::class,
            `table`  => `users`
        ]
    ],

    `password` => [
        `email` => `emails.auth.password`,
        `table` => `password_resets`,
        `expire` => 60,
    ]

];

Password Reset

如果要實現密碼重置,需要進行以下操作

首先,開啟config/app.php

替換 IlluminateAuthPasswordsPasswordResetServiceProvider::class
KbwebsMultiAuthPasswordResetsPasswordResetServiceProvider::class

AppHttpModelsUser.php

use IlluminateAuthPasswordsCanResetPassword;
use IlluminateContractsAuthCanResetPassword as CanResetPasswordContract;

替換成
use KbwebsMultiAuthPasswordResetsCanResetPassword;
use KbwebsMultiAuthPasswordResetsContractsCanResetPassword 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`))) {

即可


轉載請註明出處

相關文章