最近在使用laravel5.5,利用其實現了一個功能,下面分享給大家,這篇文章主要給大家介紹了關於Laravel 5.5基於內置的Auth模組如何實現前後台登陸的相關資料,文中通過示例程式碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。
前言
下面話不多說了,來一起看看詳細的介紹吧。
方法如下:
步驟1:產生Auth
在專案建立完成後,產生內建Auth元件:
php artisan make:auth
#步驟2:新增guard
開啟config\auth.php,為方便前後台使用者切換,項目共用Users表
'guards' => [ //... 'admin' => [ 'driver' => 'session', 'provider' => 'users', ], //... ],
#步驟3:實作基底類別
class AdminController extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { $this->middleware('auth:admin'); } }
步驟4:實作後台登陸控制器
新appcontrollersAdminLoginController.php
<?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'); } }
步驟5:實作登陸後跳到不同路徑
app\Middleware\RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { $path = $guard ? '/admin' : '/home'; return redirect($path); } return $next($request); }
#步驟6:實作未通過認證跳轉不同登陸頁面
app\Exceptions\Handler.php
/** * 重写实现未认证用户跳转至相应登陆页 * @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'); } }
完成
總結
#
以上是Laravel 5.5基於內建的Auth模組實現前後台登陸的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!