Laravel开发:多用户登录验证(2)
上一篇讲了最基本的User验证,现在来讲一下Admin的验证。
先贴代码,
路由:routes/web.php加上以下代码,
//... Route::get('admin/login', 'Admin\AuthController@showLoginForm'); Route::post('admin/login', 'Admin\AuthController@login'); Route::get('admin/register', 'Admin\AuthController@showRegistrationForm'); Route::post('admin/register', 'Admin\AuthController@register'); Route::post('admin/logout', 'Admin\AuthController@logout'); Route::get('admin', 'AdminController@index');
中间件:修改 config/auth.php 配置如下,
<?php return [ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class,//根据需要设置命名空间名 //'model' => App\Models\Admin::class, ], ], 'passwords' => [ 'users' => [ 'provider' => 'users', 'email' => 'auth.emails.password', 'table' => 'password_resets', 'expire' => 60, ], ], ];
控制器:
app/Http/Controllers/Admin/AuthController.php
代替
app/Http/Controllers/Auth/RegisterController.php 与 app/Http/Controllers/Auth/LoginController.php 所负责登录注册业务
<?php namespace App\Http\Controllers\Admin; use App\Admin; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Auth\Events\Registered; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; //use Illuminate\Foundation\Auth\RegistersUsers; class AuthController extends Controller { //use AuthenticatesUsers, ThrottlesLogins; //use RegistersUsers; use AuthenticatesUsers; protected $redirectTo = '/admin'; protected $guard = 'admin'; protected $loginView = 'admin.login'; protected $registerView = 'admin.register'; public function __construct() { $this->middleware('guest:admin', ['except' => 'logout']); //$this->middleware('guest:admin')->except('logout'); //$this->middleware('auth'); } public function showRegistrationForm(){ return view('admin.register'); } public function register(Request $request){ $this->validator($request->all())->validate(); event(new Registered($user = $this->create($request->all()))); $this->guard()->login($user); return $this->registered($request, $user) ?: redirect($this->redirectPath()); } protected function registered(Request $request, $user) { // } protected function guard() { return Auth::guard('admin'); } public function showLoginForm() { return view('admin.login'); } public function login(Request $request){ $this->validateLogin($request); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } if ($this->attemptLogin($request)) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); } public function username() { return 'email'; } public function logout(Request $request) { $this->guard()->logout(); $request->session()->flush(); $request->session()->regenerate(); return redirect('/'); } protected function validateLogin(Request $request) { $this->validate($request, [ 'email' => 'required|string', 'password' => 'required|string', ]); } protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:admin', 'password' => 'required|confirmed|min:6', ]); } protected function create(array $data) { return Admin::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } }
app/Http/Controllers/Admin/AdminController.php
代替
app/Http/Controllers/Home/HomeController.php 所负责的登陆后跳转等业务逻辑
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Auth; class AdminController extends Controller { protected $redirectTo = '/admin'; protected $guard = 'admin'; public function __construct() { $this->middleware('auth:admin'); //$this->middleware('guest:admin', ['except' => 'logout']); } public function index() { return view('admin.home'); //$admin = \Illuminate\Support\Facades\Auth::guard('admin')->user(); //return $admin->name; } }
Table表: admin
CREATE TABLE `mgshop_admin` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Model:app/Admin.php
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContracts; class Admin extends Model implements AuthenticatableContracts { use Authenticatable; protected $table = 'admin';//'admin';//设置表名 protected $primaryKey = 'id';//'AdminID';//设置主键 public $timestamps = false; protected $fillable = ['name','email','password'];//开启白名单字段 }
app/Http/Middleware/RedirectIfAuthenticated.php(在构造函数中修改 guest 中间件,用来跳转不同路由:)
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
// 根据不同 guard 跳转到不同的页面
$url = $guard ? 'admin':'/home';
return redirect($url);
}
/* if (Auth::guard($guard)->check()) {
return redirect('/home');
} */
return $next($request);
}
域名+/login
域名+/admin/login
访问测试!
此链接有类似且详细的实现方式,可做参考。Laravel 5.3 多用户表登录实现:http://laravelacademy.org/post/5925.html
版权声明:本文为博主原创文章,未经博主允许不得转载。