Laravel5.5 实现后台管理登录的方法(自定义用户表(2)

编辑 Admin/LoginController.php:

<?php 
 
namespace App\Http\Controllers\Admin; 
 
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Foundation\Auth\ThrottlesLogins; 
use Illuminate\Foundation\Auth\AuthenticatesUsers; 
 
class LoginController extends Controller 
{ 
 use AuthenticatesUsers; 
 
 /** 
  * Where to redirect users after login / registration. 
  * 
  * @var string 
  */ 
 protected $redirectTo = '/admin/index'; 
 protected $username; 
 
 /** 
  * Create a new controller instance. 
  * 
  * @return void 
  */ 
 public function __construct() 
 { 
  $this->middleware('guest:admin', ['except' => 'logout']); 
  $this->username = config('admin.global.username'); 
 } 
 
 /** 
  * 重写登录视图页面 
  */ 
 public function showLogin() 
 { 
  return view('admin.login.index'); 
 } 
 
 /** 
  * 自定义认证驱动 
  * @return mixed 
  */ 
 protected function guard() 
 { 
  return auth()->guard('admin'); 
 } 
 
 
} 

修改 app\Http\Middleware\RedirectIfAuthenticated.php:

public function handle($request, Closure $next, $guard = null) 
 { 
  if (Auth::guard($guard)->check()) { 
   // 根据不同 guard 跳转到不同的页面 
   $url = $guard ? 'admin/dash':'/home'; 
   return redirect($url); 
  } 
 
  return $next($request); 
 } 

编辑 Admin\AdminController.php:

<?php 
 
namespace App\Http\Controllers\Admin; 
 
use App\Http\Controllers\Controller; 
 
class AdminController extends Controller 
{ 
 /** 
  * Create a new controller instance. 
  * 
  * @return void 
  */ 
 public function __construct() 
 { 
  $this->middleware('auth.admin:admin'); 
 } 
 // 
 public function index() 
 { 
  dd('用户名:'.auth('admin')->user()->name); 
 } 

编辑 app\Http\Middleware\AdminAuthMiddleware.php

public function handle($request, Closure $next, $guard = null) 
 { 
  if (Auth::guard($guard)->guest()) { 
   if ($request->ajax() || $request->wantsJson()) { 
    return response('Unauthorized.', 401); 
   } else { 
    return redirect()->guest('admin/login'); 
   } 
  } 
  return $next($request); 
 } 

在 app\Http\Kernel.php 中注册:

protected $routeMiddleware = [ 
  ··· ··· 
  'auth.admin' => \App\Http\Middleware\AdminAuthMiddleware::class, 
 ]; 

注册路由

编辑 routes/web.php :

Route::group(['prefix' => 'admin','namespace' => 'Admin'],function ($router) 
{ 
 $router->get('login', 'LoginController@showLogin')->name('admin.login'); 
 $router->post('login', 'LoginController@login'); 
 $router->post('logout', 'LoginController@logout'); 
 
 $router->get('index', 'AdminController@index'); 
}); 
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5314.html