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`))) {
即可
轉載請註明出處