在項目創建完成後,生成內置Auth組件:php
php artisan make:auth
打開config\auth.php,爲方便先後臺用戶切換,項目共用Users表json
'guards' => [ //... 'admin' => [ 'driver' => 'session', 'provider' => 'users', ], //... ],
class AdminController extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { $this->middleware('auth:admin'); } }
新建appcontrollersAdminLoginController.phpsession
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/admin'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest:admin')->except('logout'); } /** * 重寫登錄頁面 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function showLoginForm() { return view('backend.login'); } /** * 重寫退出方法 * @param Request $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function logout(Request $request) { $this->guard()->logout(); $request->session()->flush(); $request->session()->regenerate(); return redirect('/admin/login'); } /** * 重寫guard認證 * @return mixed */ protected function guard() { return Auth::guard('admin'); } }
app\Middleware\RedirectIfAuthenticated.phpapp
public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { $path = $guard ? '/admin' : '/home'; return redirect($path); } return $next($request); }
app\Exceptions\Handler.phpide
/** * 重寫實現未認證用戶跳轉至相應登錄頁 * @param \Illuminate\Http\Request $request * @param AuthenticationException $exception * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function unauthenticated($request, AuthenticationException $exception) { if($request->expectsJson()){ return response()->json(['message' => $exception->getMessage()], 401); }else{ return in_array('admin', $exception->guards()) ? return redirect()->guest('/admin/login') : redirect()->guest('login'); } }
完成this