首先在config文件夹下auth.php中guards下添加
'admin' => [
'driver' => 'session', //从session
'provider' => 'admins', //内容提供是由admins
]
然后在config文件夹下auth.php中providers下添加
'admin' => [
'driver' => 'eloquent',
'model' => AppAdmin::class,//要在app文件夹下创建admin数据库orm的模型
],
在loginController中添加命名空间
use IlluminateSupportFacadesAuth;
再添加当前守卫
//在控制器当中指定当前使用的是哪一个守卫
protected function guard()
{
return Auth::guard('admin');
}
再Middleware中创建AdminAuthenticated.php,判断跳转内容如下
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class AdminAuthenticated
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::guard('admin')->check()) { //专门检查后台有没有登录
return redirect('/admin/index');//登录成功跳转地址
}
return $next($request);
}
}
然后在appHttpKernel.php加入验证
protected $routeMiddleware = [
.....
'admin'=>AdminAuthenticated::class,
或者可为这个前者要加入命名空间
'admin'=>IlluminateSupportFacadesAuthAdminAuthenticated::class,
....
];
上面蓝色部分也可使用下面此替换
protected $redirectTo = '/admin/index';
使用此守卫进行判断
public function __construct()
{
$this->middleware('admin')->except('logout');
}
在LoginController控制器中加入跳转新页面
protected $redirectTo = '/admin/index';
//使用此方法退出登录
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/admin/login');
}
再Middleware中创建AdminAuth.php,判断是否登录,内容如下
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class AdminAuth
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()) { //专门检查后台有没有登录
return redirect('/admin/login');
}
return $next($request); //没办法往下执行
}
}
然后在appHttpKernel.php加入验证
protected $routeMiddleware = [
.....
'admin-auth'=>IlluminateSupportFacadesAuthAdminAuth::class,
....
];
路由使用
Route::group(['namespace'=>'Admin','prefix'=>'admin','middleware'=>['admin-auth']],function(){
Route::get('/index','IndexController@index')->name('admin/index');
});